﻿using System;
using System.IO;
using System.Collections.Generic;
using System.ComponentModel;
using System.Reflection;
using System.Data;
using System.Drawing;
using System.Drawing.Imaging;
using System.Diagnostics;
using System.Text;
using System.Threading;
using System.Runtime;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters;
using System.Runtime.Serialization.Formatters.Binary;

using PickGold;
using PickGold.Api;
using PickGold.Base;
using PickGold.Collections;

using BaseCommon = PickGold.Base.Common;

namespace PickGold.Base.OCR
{

	/*

	[ComVisible(true)]
	[ClassInterface(ClassInterfaceType.AutoDispatch)]
	public class QRCode
	{
	}

	/// <summary>
	/// Enumerates barcode formats known to this package. Please keep alphabetized.
	/// </summary>
	public enum BarcodeFormat
	{

		/// <summary>
		/// Aztec 2D barcode format. </summary>
		AZTEC,

		/// <summary>
		/// CODABAR 1D format. </summary>
		CODABAR,

		/// <summary>
		/// Code 39 1D format. </summary>
		CODE_39,

		/// <summary>
		/// Code 93 1D format. </summary>
		CODE_93,

		/// <summary>
		/// Code 128 1D format. </summary>
		CODE_128,

		/// <summary>
		/// Data Matrix 2D barcode format. </summary>
		DATA_MATRIX,

		/// <summary>
		/// EAN-8 1D format. </summary>
		EAN_8,

		/// <summary>
		/// EAN-13 1D format. </summary>
		EAN_13,

		/// <summary>
		/// ITF (Interleaved Two of Five) 1D format. </summary>
		ITF,

		/// <summary>
		/// MaxiCode 2D barcode format. </summary>
		MAXICODE,

		/// <summary>
		/// PDF417 format. </summary>
		PDF_417,

		/// <summary>
		/// QR Code 2D barcode format. </summary>
		QR_CODE,

		/// <summary>
		/// RSS 14 </summary>
		RSS_14,

		/// <summary>
		/// RSS EXPANDED </summary>
		RSS_EXPANDED,

		/// <summary>
		/// UPC-A 1D format. </summary>
		UPC_A,

		/// <summary>
		/// UPC-E 1D format. </summary>
		UPC_E,

		/// <summary>
		/// UPC/EAN extension format. Not a stand-alone format. </summary>
		UPC_EAN_EXTENSION
	}

	/// <summary>
	/// Encapsulates a type of hint that a caller may pass to a barcode reader to help it
	/// more quickly or accurately decode it. It is up to implementations to decide what,
	/// if anything, to do with the information that is supplied.
	/// 
	/// @author Sean Owen
	/// @author dswitkin@google.com (Daniel Switkin) </summary>
	/// <seealso cref= Reader#decode(BinaryBitmap,java.util.Map) </seealso>
	public enum DecodeHintType
	{

		/// <summary>
		/// Unspecified, application-specific hint. Maps to an unspecified <seealso cref="Object"/>.
		/// </summary>
		OTHER,

		/// <summary>
		/// Image is a pure monochrome image of a barcode. Doesn't matter what it maps to;
		/// use <seealso cref="Boolean#TRUE"/>.
		/// </summary>
		PURE_BARCODE,

		/// <summary>
		/// Image is known to be of one of a few possible formats.
		/// Maps to a <seealso cref="java.util.List"/> of <seealso cref="BarcodeFormat"/>s.
		/// </summary>
		POSSIBLE_FORMATS,

		/// <summary>
		/// Spend more time to try to find a barcode; optimize for accuracy, not speed.
		/// Doesn't matter what it maps to; use <seealso cref="Boolean#TRUE"/>.
		/// </summary>
		TRY_HARDER,

		/// <summary>
		/// Specifies what character encoding to use when decoding, where applicable (type String)
		/// </summary>
		CHARACTER_SET,

		/// <summary>
		/// Allowed lengths of encoded data -- reject anything else. Maps to an int[].
		/// </summary>
		ALLOWED_LENGTHS,

		/// <summary>
		/// Assume Code 39 codes employ a check digit. Maps to <seealso cref="Boolean"/>.
		/// </summary>
		ASSUME_CODE_39_CHECK_DIGIT,

		/// <summary>
		/// The caller needs to be notified via callback when a possible <seealso cref="ResultPoint"/>
		/// is found. Maps to a <seealso cref="ResultPointCallback"/>.
		/// </summary>
		NEED_RESULT_POINT_CALLBACK,

	}

	/// <summary>
	/// These are a set of hints that you may pass to Writers to specify their behavior.
	/// 
	/// @author dswitkin@google.com (Daniel Switkin)
	/// </summary>
	public enum EncodeHintType
	{

		/// <summary>
		/// Specifies what degree of error correction to use, for example in QR Codes.
		/// Type depends on the encoder. For example for QR codes it's type
		/// <seealso cref="com.google.zxing.qrcode.decoder.ErrorCorrectionLevel ErrorCorrectionLevel"/>.
		/// </summary>
		ERROR_CORRECTION,

		/// <summary>
		/// Specifies what character encoding to use where applicable (type <seealso cref="String"/>)
		/// </summary>
		CHARACTER_SET,

		/// <summary>
		/// Specifies margin, in pixels, to use when generating the barcode. The meaning can vary
		/// by format; for example it controls margin before and after the barcode horizontally for
		/// most 1D formats. (Type <seealso cref="Integer"/>).
		/// </summary>
		MARGIN,

		/// <summary>
		/// Specifies whether to use compact mode for PDF417 (type <seealso cref="Boolean"/>).
		/// </summary>
		PDF417_COMPACT,

		/// <summary>
		/// Specifies what compaction mode to use for PDF417 (type
		/// <seealso cref="com.google.zxing.pdf417.encoder.Compaction Compaction"/>).
		/// </summary>
		PDF417_COMPACTION,

		/// <summary>
		/// Specifies the minimum and maximum number of rows and columns for PDF417 (type
		/// <seealso cref="com.google.zxing.pdf417.encoder.Dimensions Dimensions"/>).
		/// </summary>
		PDF417_DIMENSIONS,

	}

	/// <summary>
	/// Represents some type of metadata about the result of the decoding that the decoder
	/// wishes to communicate back to the caller.
	/// 
	/// @author Sean Owen
	/// </summary>
	public enum ResultMetadataType
	{

		/// <summary>
		/// Unspecified, application-specific metadata. Maps to an unspecified <seealso cref="Object"/>.
		/// </summary>
		OTHER,

		/// <summary>
		/// Denotes the likely approximate orientation of the barcode in the image. This value
		/// is given as degrees rotated clockwise from the normal, upright orientation.
		/// For example a 1D barcode which was found by reading top-to-bottom would be
		/// said to have orientation "90". This key maps to an <seealso cref="Integer"/> whose
		/// value is in the range [0,360).
		/// </summary>
		ORIENTATION,

		/// <summary>
		/// <p>2D barcode formats typically encode text, but allow for a sort of 'byte mode'
		/// which is sometimes used to encode binary data. While <seealso cref="Result"/> makes available
		/// the complete raw bytes in the barcode for these formats, it does not offer the bytes
		/// from the byte segments alone.</p>
		/// 
		/// <p>This maps to a <seealso cref="java.util.List"/> of byte arrays corresponding to the
		/// raw bytes in the byte segments in the barcode, in order.</p>
		/// </summary>
		BYTE_SEGMENTS,

		/// <summary>
		/// Error correction level used, if applicable. The value type depends on the
		/// format, but is typically a String.
		/// </summary>
		ERROR_CORRECTION_LEVEL,

		/// <summary>
		/// For some periodicals, indicates the issue number as an <seealso cref="Integer"/>.
		/// </summary>
		ISSUE_NUMBER,

		/// <summary>
		/// For some products, indicates the suggested retail price in the barcode as a
		/// formatted <seealso cref="String"/>.
		/// </summary>
		SUGGESTED_PRICE,

		/// <summary>
		/// For some products, the possible country of manufacture as a <seealso cref="String"/> denoting the
		/// ISO country code. Some map to multiple possible countries, like "US/CA".
		/// </summary>
		POSSIBLE_COUNTRY,

		/// <summary>
		/// For some products, the extension text
		/// </summary>
		UPC_EAN_EXTENSION,

	}

	/// <summary>
	/// Callback which is invoked when a possible result point (significant
	/// point in the barcode image such as a corner) is found.
	/// </summary>
	/// <seealso cref= DecodeHintType#NEED_RESULT_POINT_CALLBACK </seealso>
	public interface ResultPointCallback
	{

		void foundPossibleResultPoint(ResultPoint point);

	}

	/// <summary>
	/// The general exception class throw when something goes wrong during decoding of a barcode.
	/// This includes, but is not limited to, failing checksums / error correction algorithms, being
	/// unable to locate finder timing patterns, and so on.
	/// 
	/// @author Sean Owen
	/// </summary>
	public abstract class ReaderException : Exception
	{

		internal ReaderException()
		{
			// do nothing
		}

		// Prevent stack traces from being taken
		// srowen says: huh, my IDE is saying this is not an override. native methods can't be overridden?
		// This, at least, does not hurt. Because we use a singleton pattern here, it doesn't matter anyhow.
		public Exception fillInStackTrace()
		{
			return null;
		}

	}

	/// <summary>
	/// A base class which covers the range of exceptions which may occur when encoding a barcode using
	/// the Writer framework.
	/// </summary>
	public sealed class WriterException : Exception
	{

		public WriterException()
		{
		}

		public WriterException(string message)
			: base(message)
		{
		}

		public WriterException(Exception cause)
			: base(cause.Message, cause)
		{
		}

	}

	/// <summary>
	/// Implementations of this interface can decode an image of a barcode in some format into
	/// the String it encodes. For example, <seealso cref="com.google.zxing.qrcode.QRCodeReader"/> can
	/// decode a QR code. The decoder may optionally receive hints from the caller which may help
	/// it decode more quickly or accurately.
	/// 
	/// See <seealso cref="com.google.zxing.MultiFormatReader"/>, which attempts to determine what barcode
	/// format is present within the image as well, and then decodes it accordingly.
	/// 
	/// @author Sean Owen
	/// @author dswitkin@google.com (Daniel Switkin)
	/// </summary>
	public interface Reader
	{

		/// <summary>
		/// Locates and decodes a barcode in some format within an image.
		/// </summary>
		/// <param name="image"> image of barcode to decode </param>
		/// <returns> String which the barcode encodes </returns>
		/// <exception cref="NotFoundException"> if the barcode cannot be located or decoded for any reason </exception>
		//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET:
		//ORIGINAL LINE: Result decode(BinaryBitmap image) throws NotFoundException, ChecksumException, FormatException;
		Result decode(BinaryBitmap image);

		/// <summary>
		/// Locates and decodes a barcode in some format within an image. This method also accepts
		/// hints, each possibly associated to some data, which may help the implementation decode.
		/// </summary>
		/// <param name="image"> image of barcode to decode </param>
		/// <param name="hints"> passed as a <seealso cref="java.util.Map"/> from <seealso cref="com.google.zxing.DecodeHintType"/>
		/// to arbitrary data. The
		/// meaning of the data depends upon the hint type. The implementation may or may not do
		/// anything with these hints. </param>
		/// <returns> String which the barcode encodes </returns>
		/// <exception cref="NotFoundException"> if the barcode cannot be located or decoded for any reason </exception>
		//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET:
		//ORIGINAL LINE: Result decode(BinaryBitmap image, java.util.Map<DecodeHintType,?> hints) throws NotFoundException, ChecksumException, FormatException;
		Result decode(BinaryBitmap image, IDictionary<DecodeHintType, object> hints);

		/// <summary>
		/// Resets any internal state the implementation has after a decode, to prepare it
		/// for reuse.
		/// </summary>
		void reset();

	}

	/// <summary>
	/// The base class for all objects which encode/generate a barcode image.
	/// </summary>
	public interface Writer
	{

		/// <summary>
		/// Encode a barcode using the default settings.
		/// </summary>
		/// <param name="contents"> The contents to encode in the barcode </param>
		/// <param name="format"> The barcode format to generate </param>
		/// <param name="width"> The preferred width in pixels </param>
		/// <param name="height"> The preferred height in pixels </param>
		//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET:
		//ORIGINAL LINE: com.google.zxing.common.BitMatrix encode(String contents, BarcodeFormat format, int width, int height) throws WriterException;
		BitMatrix encode(string contents, BarcodeFormat format, int width, int height);

		/// 
		/// <param name="contents"> The contents to encode in the barcode </param>
		/// <param name="format"> The barcode format to generate </param>
		/// <param name="width"> The preferred width in pixels </param>
		/// <param name="height"> The preferred height in pixels </param>
		/// <param name="hints"> Additional parameters to supply to the encoder </param>
		//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET:
		//ORIGINAL LINE: com.google.zxing.common.BitMatrix encode(String contents, BarcodeFormat format, int width, int height, java.util.Map<EncodeHintType,?> hints) throws WriterException;
		BitMatrix encode(string contents, BarcodeFormat format, int width, int height, IDictionary<EncodeHintType, object> hints);

	}

	/// <summary>
	/// The purpose of this class hierarchy is to abstract different bitmap implementations across
	/// platforms into a standard interface for requesting greyscale luminance values. The interface
	/// only provides immutable methods; therefore crop and rotation create copies. This is to ensure
	/// that one Reader does not modify the original luminance source and leave it in an unknown state
	/// for other Readers in the chain.
	/// 
	/// @author dswitkin@google.com (Daniel Switkin)
	/// </summary>
	public abstract class LuminanceSource
	{

		private readonly int width;
		private readonly int height;

		protected internal LuminanceSource(int width, int height)
		{
			this.width = width;
			this.height = height;
		}

		/// <summary>
		/// Fetches one row of luminance data from the underlying platform's bitmap. Values range from
		/// 0 (black) to 255 (white). Because Java does not have an unsigned byte type, callers will have
		/// to bitwise and with 0xff for each value. It is preferable for implementations of this method
		/// to only fetch this row rather than the whole image, since no 2D Readers may be installed and
		/// getMatrix() may never be called.
		/// </summary>
		/// <param name="y"> The row to fetch, 0 <= y < getHeight(). </param>
		/// <param name="row"> An optional preallocated array. If null or too small, it will be ignored.
		///            Always use the returned object, and ignore the .length of the array. </param>
		/// <returns> An array containing the luminance data. </returns>
		public abstract sbyte[] getRow(int y, sbyte[] row);

		/// <summary>
		/// Fetches luminance data for the underlying bitmap. Values should be fetched using:
		/// int luminance = array[y * width + x] & 0xff;
		/// </summary>
		/// <returns> A row-major 2D array of luminance values. Do not use result.length as it may be
		///         larger than width * height bytes on some platforms. Do not modify the contents
		///         of the result. </returns>
		public abstract sbyte[] Matrix { get; }

		/// <returns> The width of the bitmap. </returns>
		public int Width
		{
			get
			{
				return width;
			}
		}

		/// <returns> The height of the bitmap. </returns>
		public int Height
		{
			get
			{
				return height;
			}
		}

		/// <returns> Whether this subclass supports cropping. </returns>
		public virtual bool CropSupported
		{
			get
			{
				return false;
			}
		}

		/// <summary>
		/// Returns a new object with cropped image data. Implementations may keep a reference to the
		/// original data rather than a copy. Only callable if isCropSupported() is true.
		/// </summary>
		/// <param name="left"> The left coordinate, 0 <= left < getWidth(). </param>
		/// <param name="top"> The top coordinate, 0 <= top <= getHeight(). </param>
		/// <param name="width"> The width of the rectangle to crop. </param>
		/// <param name="height"> The height of the rectangle to crop. </param>
		/// <returns> A cropped version of this object. </returns>
		public virtual LuminanceSource crop(int left, int top, int width, int height)
		{
			throw new System.NotSupportedException("This luminance source does not support cropping.");
		}

		/// <returns> Whether this subclass supports counter-clockwise rotation. </returns>
		public virtual bool RotateSupported
		{
			get
			{
				return false;
			}
		}

		/// <summary>
		/// Returns a new object with rotated image data by 90 degrees counterclockwise.
		/// Only callable if <seealso cref="#isRotateSupported()"/> is true.
		/// </summary>
		/// <returns> A rotated version of this object. </returns>
		public virtual LuminanceSource rotateCounterClockwise()
		{
			throw new System.NotSupportedException("This luminance source does not support rotation by 90 degrees.");
		}

		/// <summary>
		/// Returns a new object with rotated image data by 45 degrees counterclockwise.
		/// Only callable if <seealso cref="#isRotateSupported()"/> is true.
		/// </summary>
		/// <returns> A rotated version of this object. </returns>
		public virtual LuminanceSource rotateCounterClockwise45()
		{
			throw new System.NotSupportedException("This luminance source does not support rotation by 45 degrees.");
		}

		public override string ToString()
		{
			sbyte[] row = new sbyte[width];
			StringBuilder result = new StringBuilder(height * (width + 1));
			for (int y = 0; y < height; y++)
			{
				row = getRow(y, row);
				for (int x = 0; x < width; x++)
				{
					int luminance = row[x] & 0xFF;
					char c;
					if (luminance < 0x40)
					{
						c = '#';
					}
					else if (luminance < 0x80)
					{
						c = '+';
					}
					else if (luminance < 0xC0)
					{
						c = '.';
					}
					else
					{
						c = ' ';
					}
					result.Append(c);
				}
				result.Append('\n');
			}
			return result.ToString();
		}

	}

	/// <summary>
	/// MultiFormatReader is a convenience class and the main entry point into the library for most uses.
	/// By default it attempts to decode all barcode formats that the library supports. Optionally, you
	/// can provide a hints object to request different behavior, for example only decoding QR codes.
	/// 
	/// @author Sean Owen
	/// @author dswitkin@google.com (Daniel Switkin)
	/// </summary>
	public sealed class MultiFormatReader : Reader
	{

		//JAVA TO C# CONVERTER TODO TASK: Java wildcard generics are not converted to .NET:
		//ORIGINAL LINE: private java.util.Map<DecodeHintType,?> hints;
		private IDictionary<DecodeHintType, object> hints;
		private Reader[] readers;

		/// <summary>
		/// This version of decode honors the intent of Reader.decode(BinaryBitmap) in that it
		/// passes null as a hint to the decoders. However, that makes it inefficient to call repeatedly.
		/// Use setHints() followed by decodeWithState() for continuous scan applications.
		/// </summary>
		/// <param name="image"> The pixel data to decode </param>
		/// <returns> The contents of the image </returns>
		/// <exception cref="NotFoundException"> Any errors which occurred </exception>
		//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET:
		//ORIGINAL LINE: public Result decode(BinaryBitmap image) throws NotFoundException
		public Result decode(BinaryBitmap image)
		{
			Hints = null;
			return decodeInternal(image);
		}

		/// <summary>
		/// Decode an image using the hints provided. Does not honor existing state.
		/// </summary>
		/// <param name="image"> The pixel data to decode </param>
		/// <param name="hints"> The hints to use, clearing the previous state. </param>
		/// <returns> The contents of the image </returns>
		/// <exception cref="NotFoundException"> Any errors which occurred </exception>
		//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET:
		//ORIGINAL LINE: public Result decode(BinaryBitmap image, java.util.Map<DecodeHintType,?> hints) throws NotFoundException
		public Result decode(BinaryBitmap image, IDictionary<DecodeHintType, object> hints)
		{
			Hints = hints;
			return decodeInternal(image);
		}

		/// <summary>
		/// Decode an image using the state set up by calling setHints() previously. Continuous scan
		/// clients will get a <b>large</b> speed increase by using this instead of decode().
		/// </summary>
		/// <param name="image"> The pixel data to decode </param>
		/// <returns> The contents of the image </returns>
		/// <exception cref="NotFoundException"> Any errors which occurred </exception>
		//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET:
		//ORIGINAL LINE: public Result decodeWithState(BinaryBitmap image) throws NotFoundException
		public Result decodeWithState(BinaryBitmap image)
		{
			// Make sure to set up the default state so we don't crash
			if (readers == null)
			{
				Hints = null;
			}
			return decodeInternal(image);
		}

		/// <summary>
		/// This method adds state to the MultiFormatReader. By setting the hints once, subsequent calls
		/// to decodeWithState(image) can reuse the same set of readers without reallocating memory. This
		/// is important for performance in continuous scan clients.
		/// </summary>
		/// <param name="hints"> The set of hints to use for subsequent calls to decode(image) </param>
		public IDictionary<DecodeHintType, object> Hints
		{
			set
			{
				this.hints = value;

				bool tryHarder = value != null && value.ContainsKey(DecodeHintType.TRY_HARDER);

				//ICollection<BarcodeFormat> formats = value == null ? null : (ICollection<BarcodeFormat>) value[DecodeHintType.POSSIBLE_FORMATS];
				ICollection<BarcodeFormat> formats = null;
				if (value != null && value.ContainsKey(DecodeHintType.POSSIBLE_FORMATS))
				{
					formats = (ICollection<BarcodeFormat>)value[DecodeHintType.POSSIBLE_FORMATS];
				}
				List<Reader> readers = new List<Reader>();
				if (formats != null)
				{
					bool addOneDReader = formats.Contains(BarcodeFormat.UPC_A) || formats.Contains(BarcodeFormat.UPC_E) || formats.Contains(BarcodeFormat.EAN_13) || formats.Contains(BarcodeFormat.EAN_8) || formats.Contains(BarcodeFormat.CODABAR) || formats.Contains(BarcodeFormat.CODE_39) || formats.Contains(BarcodeFormat.CODE_93) || formats.Contains(BarcodeFormat.CODE_128) || formats.Contains(BarcodeFormat.ITF) || formats.Contains(BarcodeFormat.RSS_14) || formats.Contains(BarcodeFormat.RSS_EXPANDED);
					// Put 1D readers upfront in "normal" mode
					if (addOneDReader && !tryHarder)
					{
						readers.Add(new MultiFormatOneDReader(value));
					}
					if (formats.Contains(BarcodeFormat.QR_CODE))
					{
						readers.Add(new QRCodeReader());
					}
					if (formats.Contains(BarcodeFormat.DATA_MATRIX))
					{
						readers.Add(new DataMatrixReader());
					}
					if (formats.Contains(BarcodeFormat.AZTEC))
					{
						readers.Add(new AztecReader());
					}
					if (formats.Contains(BarcodeFormat.PDF_417))
					{
						readers.Add(new PDF417Reader());
					}
					if (formats.Contains(BarcodeFormat.MAXICODE))
					{
						readers.Add(new MaxiCodeReader());
					}
					// At end in "try harder" mode
					if (addOneDReader && tryHarder)
					{
						readers.Add(new MultiFormatOneDReader(value));
					}
				}
				if (readers.Count == 0)
				{
					if (!tryHarder)
					{
						readers.Add(new MultiFormatOneDReader(value));
					}

					readers.Add(new QRCodeReader());
					readers.Add(new DataMatrixReader());
					readers.Add(new AztecReader());
					readers.Add(new PDF417Reader());
					readers.Add(new MaxiCodeReader());

					if (tryHarder)
					{
						readers.Add(new MultiFormatOneDReader(value));
					}
				}
				this.readers = readers.ToArray();//this.readers = readers.ToArray(new Reader[readers.Count]);
			}
		}

		public void reset()
		{
			if (readers != null)
			{
				foreach (Reader reader in readers)
				{
					reader.reset();
				}
			}
		}

		//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET:
		//ORIGINAL LINE: private Result decodeInternal(BinaryBitmap image) throws NotFoundException
		private Result decodeInternal(BinaryBitmap image)
		{
			if (readers != null)
			{
				foreach (Reader reader in readers)
				{
					try
					{
						return reader.decode(image, hints);
					}
					catch (ReaderException re)
					{
						// continue
					}
				}
			}
			throw NotFoundException.NotFoundInstance;
		}

	}

	/// <summary>
	/// This is a factory class which finds the appropriate Writer subclass for the BarcodeFormat
	/// requested and encodes the barcode with the supplied contents.
	/// 
	/// @author dswitkin@google.com (Daniel Switkin)
	/// </summary>
	public sealed class MultiFormatWriter : Writer
	{

		//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET:
		//ORIGINAL LINE: public com.google.zxing.common.BitMatrix encode(String contents, BarcodeFormat format, int width, int height) throws WriterException
		public BitMatrix encode(string contents, BarcodeFormat format, int width, int height)
		{
			return encode(contents, format, width, height, null);
		}

		//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET:
		//ORIGINAL LINE: public com.google.zxing.common.BitMatrix encode(String contents, BarcodeFormat format, int width, int height, java.util.Map<EncodeHintType,?> hints) throws WriterException
		public BitMatrix encode(string contents, BarcodeFormat format, int width, int height, IDictionary<EncodeHintType, object> hints)
		{

			Writer writer;
			switch (format)
			{
				case com.google.zxing.BarcodeFormat.EAN_8:
					writer = new EAN8Writer();
					break;
				case com.google.zxing.BarcodeFormat.EAN_13:
					writer = new EAN13Writer();
					break;
				case com.google.zxing.BarcodeFormat.UPC_A:
					writer = new UPCAWriter();
					break;
				case com.google.zxing.BarcodeFormat.QR_CODE:
					writer = new QRCodeWriter();
					break;
				case com.google.zxing.BarcodeFormat.CODE_39:
					writer = new Code39Writer();
					break;
				case com.google.zxing.BarcodeFormat.CODE_128:
					writer = new Code128Writer();
					break;
				case com.google.zxing.BarcodeFormat.ITF:
					writer = new ITFWriter();
					break;
				case com.google.zxing.BarcodeFormat.PDF_417:
					writer = new PDF417Writer();
					break;
				case com.google.zxing.BarcodeFormat.CODABAR:
					writer = new CodaBarWriter();
					break;
				default:
					throw new System.ArgumentException("No encoder available for format " + format);
			}
			return writer.encode(contents, format, width, height, hints);
		}

	}

	/// <summary>
	/// This class is used to help decode images from files which arrive as RGB data from
	/// an ARGB pixel array. It does not support rotation.
	/// 
	/// @author dswitkin@google.com (Daniel Switkin)
	/// @author Betaminos
	/// </summary>
	public sealed class RGBLuminanceSource : LuminanceSource
	{

		private readonly sbyte[] luminances;
		private readonly int dataWidth;
		private readonly int dataHeight;
		private readonly int left;
		private readonly int top;

		public RGBLuminanceSource(int width, int height, int[] pixels)
			: base(width, height)
		{

			dataWidth = width;
			dataHeight = height;
			left = 0;
			top = 0;

			// In order to measure pure decoding speed, we convert the entire image to a greyscale array
			// up front, which is the same as the Y channel of the YUVLuminanceSource in the real app.
			luminances = new sbyte[width * height];
			for (int y = 0; y < height; y++)
			{
				int offset = y * width;
				for (int x = 0; x < width; x++)
				{
					int pixel = pixels[offset + x];
					int r = (pixel >> 16) & 0xff;
					int g = (pixel >> 8) & 0xff;
					int b = pixel & 0xff;
					if (r == g && g == b)
					{
						// Image is already greyscale, so pick any channel.
						luminances[offset + x] = (sbyte)r;
					}
					else
					{
						// Calculate luminance cheaply, favoring green.
						luminances[offset + x] = (sbyte)((r + g + g + b) >> 2);
					}
				}
			}
		}

		private RGBLuminanceSource(sbyte[] pixels, int dataWidth, int dataHeight, int left, int top, int width, int height)
			: base(width, height)
		{
			if (left + width > dataWidth || top + height > dataHeight)
			{
				throw new System.ArgumentException("Crop rectangle does not fit within image data.");
			}
			this.luminances = pixels;
			this.dataWidth = dataWidth;
			this.dataHeight = dataHeight;
			this.left = left;
			this.top = top;
		}

		public RGBLuminanceSource(Bitmap d, int W, int H)
			: base(W, H)
		{
			int width = dataWidth = W;
			int height = dataHeight = H;
			// In order to measure pure decoding speed, we convert the entire image to a greyscale array
			// up front, which is the same as the Y channel of the YUVLuminanceSource in the real app.
			luminances = new sbyte[width * height];
			//if (format == PixelFormat.Format8bppIndexed)
			{
				Color c;
				for (int y = 0; y < height; y++)
				{
					int offset = y * width;
					for (int x = 0; x < width; x++)
					{
						c = d.GetPixel(x, y);
						luminances[offset + x] = (sbyte)(((int)c.R) << 16 | ((int)c.G) << 8 | ((int)c.B));
					}
				}
			}
		}

		public override sbyte[] getRow(int y, sbyte[] row)
		{
			if (y < 0 || y >= Height)
			{
				throw new System.ArgumentException("Requested row is outside the image: " + y);
			}
			int width = Width;
			if (row == null || row.Length < width)
			{
				row = new sbyte[width];
			}
			int offset = (y + top) * dataWidth + left;
			Array.Copy(luminances, offset, row, 0, width);
			return row;
		}

		public override sbyte[] Matrix
		{
			get
			{
				int width = Width;
				int height = Height;

				// If the caller asks for the entire underlying image, save the copy and give them the
				// original data. The docs specifically warn that result.length must be ignored.
				if (width == dataWidth && height == dataHeight)
				{
					return luminances;
				}

				int area = width * height;
				sbyte[] matrix = new sbyte[area];
				int inputOffset = top * dataWidth + left;

				// If the width matches the full width of the underlying data, perform a single copy.
				if (width == dataWidth)
				{
					Array.Copy(luminances, inputOffset, matrix, 0, area);
					return matrix;
				}

				// Otherwise copy one cropped row at a time.
				sbyte[] rgb = luminances;
				for (int y = 0; y < height; y++)
				{
					int outputOffset = y * width;
					Array.Copy(rgb, inputOffset, matrix, outputOffset, width);
					inputOffset += dataWidth;
				}
				return matrix;
			}
		}

		public override bool CropSupported
		{
			get
			{
				return true;
			}
		}

		public override LuminanceSource crop(int left, int top, int width, int height)
		{
			return new RGBLuminanceSource(luminances, dataWidth, dataHeight, this.left + left, this.top + top, width, height);
		}

	}

	/// <summary>
	/// This class hierarchy provides a set of methods to convert luminance data to 1 bit data.
	/// It allows the algorithm to vary polymorphically, for example allowing a very expensive
	/// thresholding technique for servers and a fast one for mobile. It also permits the implementation
	/// to vary, e.g. a JNI version for Android and a Java fallback version for other platforms.
	/// 
	/// @author dswitkin@google.com (Daniel Switkin)
	/// </summary>
	public abstract class Binarizer
	{

		private readonly LuminanceSource source;

		protected internal Binarizer(LuminanceSource source)
		{
			this.source = source;
		}

		public LuminanceSource LuminanceSource
		{
			get
			{
				return source;
			}
		}

		/// <summary>
		/// Converts one row of luminance data to 1 bit data. May actually do the conversion, or return
		/// cached data. Callers should assume this method is expensive and call it as seldom as possible.
		/// This method is intended for decoding 1D barcodes and may choose to apply sharpening.
		/// For callers which only examine one row of pixels at a time, the same BitArray should be reused
		/// and passed in with each call for performance. However it is legal to keep more than one row
		/// at a time if needed.
		/// </summary>
		/// <param name="y"> The row to fetch, 0 <= y < bitmap height. </param>
		/// <param name="row"> An optional preallocated array. If null or too small, it will be ignored.
		///            If used, the Binarizer will call BitArray.clear(). Always use the returned object. </param>
		/// <returns> The array of bits for this row (true means black). </returns>
		//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET:
		//ORIGINAL LINE: public abstract com.google.zxing.common.BitArray getBlackRow(int y, com.google.zxing.common.BitArray row) throws NotFoundException;
		public abstract BitArray getBlackRow(int y, BitArray row);

		/// <summary>
		/// Converts a 2D array of luminance data to 1 bit data. As above, assume this method is expensive
		/// and do not call it repeatedly. This method is intended for decoding 2D barcodes and may or
		/// may not apply sharpening. Therefore, a row from this matrix may not be identical to one
		/// fetched using getBlackRow(), so don't mix and match between them.
		/// </summary>
		/// <returns> The 2D array of bits for the image (true means black). </returns>
		//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET:
		//ORIGINAL LINE: public abstract com.google.zxing.common.BitMatrix getBlackMatrix() throws NotFoundException;
		public abstract BitMatrix BlackMatrix { get; }

		/// <summary>
		/// Creates a new object with the same type as this Binarizer implementation, but with pristine
		/// state. This is needed because Binarizer implementations may be stateful, e.g. keeping a cache
		/// of 1 bit data. See Effective Java for why we can't use Java's clone() method.
		/// </summary>
		/// <param name="source"> The LuminanceSource this Binarizer will operate on. </param>
		/// <returns> A new concrete Binarizer implementation object. </returns>
		public abstract Binarizer createBinarizer(LuminanceSource source);

		public int Width
		{
			get
			{
				return source.Width;
			}
		}

		public int Height
		{
			get
			{
				return source.Height;
			}
		}

	}

	/// <summary>
	/// This class is the core bitmap class used by ZXing to represent 1 bit data. Reader objects
	/// accept a BinaryBitmap and attempt to decode it.
	/// 
	/// @author dswitkin@google.com (Daniel Switkin)
	/// </summary>
	public sealed class BinaryBitmap
	{

		private readonly Binarizer binarizer;
		private BitMatrix matrix;

		public BinaryBitmap(Binarizer binarizer)
		{
			if (binarizer == null)
			{
				throw new System.ArgumentException("Binarizer must be non-null.");
			}
			this.binarizer = binarizer;
		}

		/// <returns> The width of the bitmap. </returns>
		public int Width
		{
			get
			{
				return binarizer.Width;
			}
		}

		/// <returns> The height of the bitmap. </returns>
		public int Height
		{
			get
			{
				return binarizer.Height;
			}
		}

		/// <summary>
		/// Converts one row of luminance data to 1 bit data. May actually do the conversion, or return
		/// cached data. Callers should assume this method is expensive and call it as seldom as possible.
		/// This method is intended for decoding 1D barcodes and may choose to apply sharpening.
		/// </summary>
		/// <param name="y"> The row to fetch, 0 <= y < bitmap height. </param>
		/// <param name="row"> An optional preallocated array. If null or too small, it will be ignored.
		///            If used, the Binarizer will call BitArray.clear(). Always use the returned object. </param>
		/// <returns> The array of bits for this row (true means black). </returns>
		//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET:
		//ORIGINAL LINE: public com.google.zxing.common.BitArray getBlackRow(int y, com.google.zxing.common.BitArray row) throws NotFoundException
		public BitArray getBlackRow(int y, BitArray row)
		{
			return binarizer.getBlackRow(y, row);
		}

		/// <summary>
		/// Converts a 2D array of luminance data to 1 bit. As above, assume this method is expensive
		/// and do not call it repeatedly. This method is intended for decoding 2D barcodes and may or
		/// may not apply sharpening. Therefore, a row from this matrix may not be identical to one
		/// fetched using getBlackRow(), so don't mix and match between them.
		/// </summary>
		/// <returns> The 2D array of bits for the image (true means black). </returns>
		//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET:
		//ORIGINAL LINE: public com.google.zxing.common.BitMatrix getBlackMatrix() throws NotFoundException
		public BitMatrix BlackMatrix
		{
			get
			{
				// The matrix is created on demand the first time it is requested, then cached. There are two
				// reasons for this:
				// 1. This work will never be done if the caller only installs 1D Reader objects, or if a
				//    1D Reader finds a barcode before the 2D Readers run.
				// 2. This work will only be done once even if the caller installs multiple 2D Readers.
				if (matrix == null)
				{
					matrix = binarizer.BlackMatrix;
				}
				return matrix;
			}
		}

		/// <returns> Whether this bitmap can be cropped. </returns>
		public bool CropSupported
		{
			get
			{
				return binarizer.LuminanceSource.CropSupported;
			}
		}

		/// <summary>
		/// Returns a new object with cropped image data. Implementations may keep a reference to the
		/// original data rather than a copy. Only callable if isCropSupported() is true.
		/// </summary>
		/// <param name="left"> The left coordinate, 0 <= left < getWidth(). </param>
		/// <param name="top"> The top coordinate, 0 <= top <= getHeight(). </param>
		/// <param name="width"> The width of the rectangle to crop. </param>
		/// <param name="height"> The height of the rectangle to crop. </param>
		/// <returns> A cropped version of this object. </returns>
		public BinaryBitmap crop(int left, int top, int width, int height)
		{
			LuminanceSource newSource = binarizer.LuminanceSource.crop(left, top, width, height);
			return new BinaryBitmap(binarizer.createBinarizer(newSource));
		}

		/// <returns> Whether this bitmap supports counter-clockwise rotation. </returns>
		public bool RotateSupported
		{
			get
			{
				return binarizer.LuminanceSource.RotateSupported;
			}
		}

		/// <summary>
		/// Returns a new object with rotated image data by 90 degrees counterclockwise.
		/// Only callable if <seealso cref="#isRotateSupported()"/> is true.
		/// </summary>
		/// <returns> A rotated version of this object. </returns>
		public BinaryBitmap rotateCounterClockwise()
		{
			LuminanceSource newSource = binarizer.LuminanceSource.rotateCounterClockwise();
			return new BinaryBitmap(binarizer.createBinarizer(newSource));
		}

		/// <summary>
		/// Returns a new object with rotated image data by 45 degrees counterclockwise.
		/// Only callable if <seealso cref="#isRotateSupported()"/> is true.
		/// </summary>
		/// <returns> A rotated version of this object. </returns>
		public BinaryBitmap rotateCounterClockwise45()
		{
			LuminanceSource newSource = binarizer.LuminanceSource.rotateCounterClockwise45();
			return new BinaryBitmap(binarizer.createBinarizer(newSource));
		}

	}

	/// <summary>
	/// <p>Encapsulates a point of interest in an image containing a barcode. Typically, this
	/// would be the location of a finder pattern or the corner of the barcode, for example.</p>
	/// 
	/// @author Sean Owen
	/// </summary>
	public class ResultPoint
	{

		private readonly float x;
		private readonly float y;

		public ResultPoint(float x, float y)
		{
			this.x = x;
			this.y = y;
		}

		public float X
		{
			get
			{
				return x;
			}
		}

		public float Y
		{
			get
			{
				return y;
			}
		}

		public override bool Equals(object other)
		{
			if (other is ResultPoint)
			{
				ResultPoint otherPoint = (ResultPoint)other;
				return x == otherPoint.x && y == otherPoint.y;
			}
			return false;
		}

		public override int GetHashCode()
		{
			//return 31 * float.floatToIntBits(x) + float.floatToIntBits(y);

			int xbits = BitConverter.ToInt32(BitConverter.GetBytes(x), 0);
			int ybits = BitConverter.ToInt32(BitConverter.GetBytes(y), 0);
			return 31 * xbits + ybits;
		}

		public override string ToString()
		{
			StringBuilder result = new StringBuilder(25);
			result.Append('(');
			result.Append(x);
			result.Append(',');
			result.Append(y);
			result.Append(')');
			return result.ToString();
		}

		/// <summary>
		/// <p>Orders an array of three ResultPoints in an order [A,B,C] such that AB < AC and
		/// BC < AC and the angle between BC and BA is less than 180 degrees.
		/// </summary>
		public static void orderBestPatterns(ResultPoint[] patterns)
		{

			// Find distances between pattern centers
			float zeroOneDistance = distance(patterns[0], patterns[1]);
			float oneTwoDistance = distance(patterns[1], patterns[2]);
			float zeroTwoDistance = distance(patterns[0], patterns[2]);

			ResultPoint pointA;
			ResultPoint pointB;
			ResultPoint pointC;
			// Assume one closest to other two is B; A and C will just be guesses at first
			if (oneTwoDistance >= zeroOneDistance && oneTwoDistance >= zeroTwoDistance)
			{
				pointB = patterns[0];
				pointA = patterns[1];
				pointC = patterns[2];
			}
			else if (zeroTwoDistance >= oneTwoDistance && zeroTwoDistance >= zeroOneDistance)
			{
				pointB = patterns[1];
				pointA = patterns[0];
				pointC = patterns[2];
			}
			else
			{
				pointB = patterns[2];
				pointA = patterns[0];
				pointC = patterns[1];
			}

			// Use cross product to figure out whether A and C are correct or flipped.
			// This asks whether BC x BA has a positive z component, which is the arrangement
			// we want for A, B, C. If it's negative, then we've got it flipped around and
			// should swap A and C.
			if (crossProductZ(pointA, pointB, pointC) < 0.0f)
			{
				ResultPoint temp = pointA;
				pointA = pointC;
				pointC = temp;
			}

			patterns[0] = pointA;
			patterns[1] = pointB;
			patterns[2] = pointC;
		}


		/// <returns> distance between two points </returns>
		public static float distance(ResultPoint pattern1, ResultPoint pattern2)
		{
			return MathUtils.distance(pattern1.x, pattern1.y, pattern2.x, pattern2.y);
		}

		/// <summary>
		/// Returns the z component of the cross product between vectors BC and BA.
		/// </summary>
		private static float crossProductZ(ResultPoint pointA, ResultPoint pointB, ResultPoint pointC)
		{
			float bX = pointB.x;
			float bY = pointB.y;
			return ((pointC.x - bX) * (pointA.y - bY)) - ((pointC.y - bY) * (pointA.x - bX));
		}


	}

	/// <summary>
	/// <p>A simple, fast array of bits, represented compactly by an array of ints internally.</p>
	/// 
	/// @author Sean Owen
	/// </summary>
	public sealed class BitArray
	{

		private int[] bits;
		private int size;

		public BitArray()
		{
			this.size = 0;
			this.bits = new int[1];
		}

		public BitArray(int size)
		{
			this.size = size;
			this.bits = makeArray(size);
		}

		public int Size
		{
			get
			{
				return size;
			}
		}

		public int SizeInBytes
		{
			get
			{
				return (size + 7) >> 3;
			}
		}

		private void ensureCapacity(int size)
		{
			if (size > bits.Length << 5)
			{
				int[] newBits = makeArray(size);
				Array.Copy(bits, 0, newBits, 0, bits.Length);
				this.bits = newBits;
			}
		}

		/// <param name="i"> bit to get </param>
		/// <returns> true iff bit i is set </returns>
		public bool get(int i)
		{
			return (bits[i >> 5] & (1 << (i & 0x1F))) != 0;
		}

		/// <summary>
		/// Sets bit i.
		/// </summary>
		/// <param name="i"> bit to set </param>
		public void set(int i)
		{
			bits[i >> 5] |= 1 << (i & 0x1F);
		}

		/// <summary>
		/// Flips bit i.
		/// </summary>
		/// <param name="i"> bit to set </param>
		public void flip(int i)
		{
			bits[i >> 5] ^= 1 << (i & 0x1F);
		}

		/// <param name="from"> first bit to check </param>
		/// <returns> index of first bit that is set, starting from the given index, or size if none are set
		///  at or beyond this given index </returns>
		/// <seealso cref= #getNextUnset(int) </seealso>
		public int getNextSet(int from)
		{
			if (from >= size)
			{
				return size;
			}
			int bitsOffset = from >> 5;
			int currentBits = bits[bitsOffset];
			// mask off lesser bits first
			currentBits &= ~((1 << (from & 0x1F)) - 1);
			while (currentBits == 0)
			{
				if (++bitsOffset == bits.Length)
				{
					return size;
				}
				currentBits = bits[bitsOffset];
			}
			//int result = (bitsOffset << 5) + int.numberOfTrailingZeros(currentBits);
			int result = (bitsOffset << 5) + currentBits.NumberOfTrailingZeros();
			return result > size ? size : result;
		}

		/// <seealso cref= #getNextSet(int) </seealso>
		public int getNextUnset(int from)
		{
			if (from >= size)
			{
				return size;
			}
			int bitsOffset = from >> 5;
			int currentBits = ~bits[bitsOffset];
			// mask off lesser bits first
			currentBits &= ~((1 << (from & 0x1F)) - 1);
			while (currentBits == 0)
			{
				if (++bitsOffset == bits.Length)
				{
					return size;
				}
				currentBits = ~bits[bitsOffset];
			}
			//int result = (bitsOffset << 5) + int.numberOfTrailingZeros(currentBits);
			int result = (bitsOffset << 5) + currentBits.NumberOfTrailingZeros();
			return result > size ? size : result;
		}

		/// <summary>
		/// Sets a block of 32 bits, starting at bit i.
		/// </summary>
		/// <param name="i"> first bit to set </param>
		/// <param name="newBits"> the new value of the next 32 bits. Note again that the least-significant bit
		/// corresponds to bit i, the next-least-significant to i+1, and so on. </param>
		public void setBulk(int i, int newBits)
		{
			bits[i >> 5] = newBits;
		}

		/// <summary>
		/// Sets a range of bits.
		/// </summary>
		/// <param name="start"> start of range, inclusive. </param>
		/// <param name="end"> end of range, exclusive </param>
		public void setRange(int start, int end)
		{
			if (end < start)
			{
				throw new System.ArgumentException();
			}
			if (end == start)
			{
				return;
			}
			end--; // will be easier to treat this as the last actually set bit -- inclusive
			int firstInt = start >> 5;
			int lastInt = end >> 5;
			for (int i = firstInt; i <= lastInt; i++)
			{
				int firstBit = i > firstInt ? 0 : start & 0x1F;
				int lastBit = i < lastInt ? 31 : end & 0x1F;
				int mask;
				if (firstBit == 0 && lastBit == 31)
				{
					mask = -1;
				}
				else
				{
					mask = 0;
					for (int j = firstBit; j <= lastBit; j++)
					{
						mask |= 1 << j;
					}
				}
				bits[i] |= mask;
			}
		}

		/// <summary>
		/// Clears all bits (sets to false).
		/// </summary>
		public void clear()
		{
			int max = bits.Length;
			for (int i = 0; i < max; i++)
			{
				bits[i] = 0;
			}
		}

		/// <summary>
		/// Efficient method to check if a range of bits is set, or not set.
		/// </summary>
		/// <param name="start"> start of range, inclusive. </param>
		/// <param name="end"> end of range, exclusive </param>
		/// <param name="value"> if true, checks that bits in range are set, otherwise checks that they are not set </param>
		/// <returns> true iff all bits are set or not set in range, according to value argument </returns>
		/// <exception cref="IllegalArgumentException"> if end is less than or equal to start </exception>
		public bool isRange(int start, int end, bool value)
		{
			if (end < start)
			{
				throw new System.ArgumentException();
			}
			if (end == start)
			{
				return true; // empty range matches
			}
			end--; // will be easier to treat this as the last actually set bit -- inclusive
			int firstInt = start >> 5;
			int lastInt = end >> 5;
			for (int i = firstInt; i <= lastInt; i++)
			{
				int firstBit = i > firstInt ? 0 : start & 0x1F;
				int lastBit = i < lastInt ? 31 : end & 0x1F;
				int mask;
				if (firstBit == 0 && lastBit == 31)
				{
					mask = -1;
				}
				else
				{
					mask = 0;
					for (int j = firstBit; j <= lastBit; j++)
					{
						mask |= 1 << j;
					}
				}

				// Return false if we're looking for 1s and the masked bits[i] isn't all 1s (that is,
				// equals the mask, or we're looking for 0s and the masked portion is not all 0s
				if ((bits[i] & mask) != (value ? mask : 0))
				{
					return false;
				}
			}
			return true;
		}

		public void appendBit(bool bit)
		{
			ensureCapacity(size + 1);
			if (bit)
			{
				bits[size >> 5] |= 1 << (size & 0x1F);
			}
			size++;
		}

		/// <summary>
		/// Appends the least-significant bits, from value, in order from most-significant to
		/// least-significant. For example, appending 6 bits from 0x000001E will append the bits
		/// 0, 1, 1, 1, 1, 0 in that order.
		/// </summary>
		public void appendBits(int value, int numBits)
		{
			if (numBits < 0 || numBits > 32)
			{
				throw new System.ArgumentException("Num bits must be between 0 and 32");
			}
			ensureCapacity(size + numBits);
			for (int numBitsLeft = numBits; numBitsLeft > 0; numBitsLeft--)
			{
				appendBit(((value >> (numBitsLeft - 1)) & 0x01) == 1);
			}
		}

		public void appendBitArray(BitArray other)
		{
			int otherSize = other.size;
			ensureCapacity(size + otherSize);
			for (int i = 0; i < otherSize; i++)
			{
				appendBit(other.get(i));
			}
		}

		public void xor(BitArray other)
		{
			if (bits.Length != other.bits.Length)
			{
				throw new System.ArgumentException("Sizes don't match");
			}
			for (int i = 0; i < bits.Length; i++)
			{
				// The last byte could be incomplete (i.e. not have 8 bits in
				// it) but there is no problem since 0 XOR 0 == 0.
				bits[i] ^= other.bits[i];
			}
		}

		/// 
		/// <param name="bitOffset"> first bit to start writing </param>
		/// <param name="array"> array to write into. Bytes are written most-significant byte first. This is the opposite
		///  of the internal representation, which is exposed by <seealso cref="#getBitArray()"/> </param>
		/// <param name="offset"> position in array to start writing </param>
		/// <param name="numBytes"> how many bytes to write </param>
		public void toBytes(int bitOffset, sbyte[] array, int offset, int numBytes)
		{
			for (int i = 0; i < numBytes; i++)
			{
				int theByte = 0;
				for (int j = 0; j < 8; j++)
				{
					if (get(bitOffset))
					{
						theByte |= 1 << (7 - j);
					}
					bitOffset++;
				}
				array[offset + i] = (sbyte)theByte;
			}
		}

		/// <returns> underlying array of ints. The first element holds the first 32 bits, and the least
		///         significant bit is bit 0. </returns>
		public int[] BitArrayBits
		{
			get
			{
				return bits;
			}
		}

		/// <summary>
		/// Reverses all bits in the array.
		/// </summary>
		public void reverse()
		{
			int[] newBits = new int[bits.Length];
			int size = this.size;
			for (int i = 0; i < size; i++)
			{
				if (get(size - i - 1))
				{
					newBits[i >> 5] |= 1 << (i & 0x1F);
				}
			}
			bits = newBits;
		}

		private static int[] makeArray(int size)
		{
			return new int[(size + 31) >> 5];
		}

		public override string ToString()
		{
			StringBuilder result = new StringBuilder(size);
			for (int i = 0; i < size; i++)
			{
				if ((i & 0x07) == 0)
				{
					result.Append(' ');
				}
				result.Append(get(i) ? 'X' : '.');
			}
			return result.ToString();
		}

	}

	/// <summary>
	/// <p>Represents a 2D matrix of bits. In function arguments below, and throughout the common
	/// module, x is the column position, and y is the row position. The ordering is always x, y.
	/// The origin is at the top-left.</p>
	/// 
	/// <p>Internally the bits are represented in a 1-D array of 32-bit ints. However, each row begins
	/// with a new int. This is done intentionally so that we can copy out a row into a BitArray very
	/// efficiently.</p>
	/// 
	/// <p>The ordering of bits is row-major. Within each int, the least significant bits are used first,
	/// meaning they represent lower x values. This is compatible with BitArray's implementation.</p>
	/// 
	/// @author Sean Owen
	/// @author dswitkin@google.com (Daniel Switkin)
	/// </summary>
	public sealed class BitMatrix
	{

		private readonly int width;
		private readonly int height;
		private readonly int rowSize;
		private readonly int[] bits;

		// A helper to construct a square matrix.
		public BitMatrix(int dimension)
			: this(dimension, dimension)
		{
		}

		public BitMatrix(int width, int height)
		{
			if (width < 1 || height < 1)
			{
				throw new System.ArgumentException("Both dimensions must be greater than 0");
			}
			this.width = width;
			this.height = height;
			this.rowSize = (width + 31) >> 5;
			bits = new int[rowSize * height];
		}

		/// <summary>
		/// <p>Gets the requested bit, where true means black.</p>
		/// </summary>
		/// <param name="x"> The horizontal component (i.e. which column) </param>
		/// <param name="y"> The vertical component (i.e. which row) </param>
		/// <returns> value of given bit in matrix </returns>
		public bool get(int x, int y)
		{
			int offset = y * rowSize + (x >> 5);
			return (((int)((uint)bits[offset] >> (x & 0x1f))) & 1) != 0;
		}

		/// <summary>
		/// <p>Sets the given bit to true.</p>
		/// </summary>
		/// <param name="x"> The horizontal component (i.e. which column) </param>
		/// <param name="y"> The vertical component (i.e. which row) </param>
		public void set(int x, int y)
		{
			int offset = y * rowSize + (x >> 5);
			bits[offset] |= 1 << (x & 0x1f);
		}

		/// <summary>
		/// <p>Flips the given bit.</p>
		/// </summary>
		/// <param name="x"> The horizontal component (i.e. which column) </param>
		/// <param name="y"> The vertical component (i.e. which row) </param>
		public void flip(int x, int y)
		{
			int offset = y * rowSize + (x >> 5);
			bits[offset] ^= 1 << (x & 0x1f);
		}

		/// <summary>
		/// Clears all bits (sets to false).
		/// </summary>
		public void clear()
		{
			int max = bits.Length;
			for (int i = 0; i < max; i++)
			{
				bits[i] = 0;
			}
		}

		/// <summary>
		/// <p>Sets a square region of the bit matrix to true.</p>
		/// </summary>
		/// <param name="left"> The horizontal position to begin at (inclusive) </param>
		/// <param name="top"> The vertical position to begin at (inclusive) </param>
		/// <param name="width"> The width of the region </param>
		/// <param name="height"> The height of the region </param>
		public void setRegion(int left, int top, int width, int height)
		{
			if (top < 0 || left < 0)
			{
				throw new System.ArgumentException("Left and top must be nonnegative");
			}
			if (height < 1 || width < 1)
			{
				throw new System.ArgumentException("Height and width must be at least 1");
			}
			int right = left + width;
			int bottom = top + height;
			if (bottom > this.height || right > this.width)
			{
				throw new System.ArgumentException("The region must fit inside the matrix");
			}
			for (int y = top; y < bottom; y++)
			{
				int offset = y * rowSize;
				for (int x = left; x < right; x++)
				{
					bits[offset + (x >> 5)] |= 1 << (x & 0x1f);
				}
			}
		}

		/// <summary>
		/// A fast method to retrieve one row of data from the matrix as a BitArray.
		/// </summary>
		/// <param name="y"> The row to retrieve </param>
		/// <param name="row"> An optional caller-allocated BitArray, will be allocated if null or too small </param>
		/// <returns> The resulting BitArray - this reference should always be used even when passing
		///         your own row </returns>
		public BitArray getRow(int y, BitArray row)
		{
			if (row == null || row.Size < width)
			{
				row = new BitArray(width);
			}
			int offset = y * rowSize;
			for (int x = 0; x < rowSize; x++)
			{
				row.setBulk(x << 5, bits[offset + x]);
			}
			return row;
		}

		/// <param name="y"> row to set </param>
		/// <param name="row"> <seealso cref="BitArray"/> to copy from </param>
		public void setRow(int y, BitArray row)
		{
			Array.Copy(row.BitArrayBits, 0, bits, y * rowSize, rowSize);
		}

		/// <summary>
		/// This is useful in detecting the enclosing rectangle of a 'pure' barcode.
		/// </summary>
		/// <returns> {left,top,width,height} enclosing rectangle of all 1 bits, or null if it is all white </returns>
		public int[] EnclosingRectangle
		{
			get
			{
				int left = this.width;
				int top = this.height;
				int right = -1;
				int bottom = -1;

				for (int y = 0; y < this.height; y++)
				{
					for (int x32 = 0; x32 < rowSize; x32++)
					{
						int theBits = bits[y * rowSize + x32];
						if (theBits != 0)
						{
							if (y < top)
							{
								top = y;
							}
							if (y > bottom)
							{
								bottom = y;
							}
							if (x32 * 32 < left)
							{
								int bit = 0;
								while ((theBits << (31 - bit)) == 0)
								{
									bit++;
								}
								if ((x32 * 32 + bit) < left)
								{
									left = x32 * 32 + bit;
								}
							}
							if (x32 * 32 + 31 > right)
							{
								int bit = 31;
								while (((int)((uint)theBits >> bit)) == 0)
								{
									bit--;
								}
								if ((x32 * 32 + bit) > right)
								{
									right = x32 * 32 + bit;
								}
							}
						}
					}
				}

				int width = right - left;
				int height = bottom - top;

				if (width < 0 || height < 0)
				{
					return null;
				}

				return new int[] { left, top, width, height };
			}
		}

		/// <summary>
		/// This is useful in detecting a corner of a 'pure' barcode.
		/// </summary>
		/// <returns> {x,y} coordinate of top-left-most 1 bit, or null if it is all white </returns>
		public int[] TopLeftOnBit
		{
			get
			{
				int bitsOffset = 0;
				while (bitsOffset < bits.Length && bits[bitsOffset] == 0)
				{
					bitsOffset++;
				}
				if (bitsOffset == bits.Length)
				{
					return null;
				}
				int y = bitsOffset / rowSize;
				int x = (bitsOffset % rowSize) << 5;

				int theBits = bits[bitsOffset];
				int bit = 0;
				while ((theBits << (31 - bit)) == 0)
				{
					bit++;
				}
				x += bit;
				return new int[] { x, y };
			}
		}

		public int[] BottomRightOnBit
		{
			get
			{
				int bitsOffset = bits.Length - 1;
				while (bitsOffset >= 0 && bits[bitsOffset] == 0)
				{
					bitsOffset--;
				}
				if (bitsOffset < 0)
				{
					return null;
				}

				int y = bitsOffset / rowSize;
				int x = (bitsOffset % rowSize) << 5;

				int theBits = bits[bitsOffset];
				int bit = 31;
				while (((int)((uint)theBits >> bit)) == 0)
				{
					bit--;
				}
				x += bit;

				return new int[] { x, y };
			}
		}

		/// <returns> The width of the matrix </returns>
		public int Width
		{
			get
			{
				return width;
			}
		}

		/// <returns> The height of the matrix </returns>
		public int Height
		{
			get
			{
				return height;
			}
		}

		public override bool Equals(object o)
		{
			if (!(o is BitMatrix))
			{
				return false;
			}
			BitMatrix other = (BitMatrix)o;
			if (width != other.width || height != other.height || rowSize != other.rowSize || bits.Length != other.bits.Length)
			{
				return false;
			}
			for (int i = 0; i < bits.Length; i++)
			{
				if (bits[i] != other.bits[i])
				{
					return false;
				}
			}
			return true;
		}

		public override int GetHashCode()
		{
			int hash = width;
			hash = 31 * hash + width;
			hash = 31 * hash + height;
			hash = 31 * hash + rowSize;
			foreach (int bit in bits)
			{
				hash = 31 * hash + bit;
			}
			return hash;
		}

		public override string ToString()
		{
			StringBuilder result = new StringBuilder(height * (width + 1));
			for (int y = 0; y < height; y++)
			{
				for (int x = 0; x < width; x++)
				{
					result.Append(get(x, y) ? "X " : "  ");
				}
				result.Append('\n');
			}
			return result.ToString();
		}

	}

	/// <summary>
	/// <p>This provides an easy abstraction to read bits at a time from a sequence of bytes, where the
	/// number of bits read is not often a multiple of 8.</p>
	/// 
	/// <p>This class is thread-safe but not reentrant -- unless the caller modifies the bytes array
	/// it passed in, in which case all bets are off.</p>
	/// 
	/// @author Sean Owen
	/// </summary>
	public sealed class BitSource
	{

		private readonly sbyte[] bytes;
		private int byteOffset;
		private int bitOffset;

		/// <param name="bytes"> bytes from which this will read bits. Bits will be read from the first byte first.
		/// Bits are read within a byte from most-significant to least-significant bit. </param>
		public BitSource(sbyte[] bytes)
		{
			this.bytes = bytes;
		}

		/// <returns> index of next bit in current byte which would be read by the next call to <seealso cref="#readBits(int)"/>. </returns>
		public int BitOffset
		{
			get
			{
				return bitOffset;
			}
		}

		/// <returns> index of next byte in input byte array which would be read by the next call to <seealso cref="#readBits(int)"/>. </returns>
		public int ByteOffset
		{
			get
			{
				return byteOffset;
			}
		}

		/// <param name="numBits"> number of bits to read </param>
		/// <returns> int representing the bits read. The bits will appear as the least-significant
		///         bits of the int </returns>
		/// <exception cref="IllegalArgumentException"> if numBits isn't in [1,32] or more than is available </exception>
		public int readBits(int numBits)
		{
			if (numBits < 1 || numBits > 32 || numBits > available())
			{
				throw new System.ArgumentException(Convert.ToString(numBits));
			}

			int result = 0;

			// First, read remainder from current byte
			if (bitOffset > 0)
			{
				int bitsLeft = 8 - bitOffset;
				int toRead = numBits < bitsLeft ? numBits : bitsLeft;
				int bitsToNotRead = bitsLeft - toRead;
				int mask = (0xFF >> (8 - toRead)) << bitsToNotRead;
				result = (bytes[byteOffset] & mask) >> bitsToNotRead;
				numBits -= toRead;
				bitOffset += toRead;
				if (bitOffset == 8)
				{
					bitOffset = 0;
					byteOffset++;
				}
			}

			// Next read whole bytes
			if (numBits > 0)
			{
				while (numBits >= 8)
				{
					result = (result << 8) | (bytes[byteOffset] & 0xFF);
					byteOffset++;
					numBits -= 8;
				}

				// Finally read a partial byte
				if (numBits > 0)
				{
					int bitsToNotRead = 8 - numBits;
					int mask = (0xFF >> bitsToNotRead) << bitsToNotRead;
					result = (result << numBits) | ((bytes[byteOffset] & mask) >> bitsToNotRead);
					bitOffset += numBits;
				}
			}

			return result;
		}

		/// <returns> number of bits that can be read successfully </returns>
		public int available()
		{
			return 8 * (bytes.Length - byteOffset) - bitOffset;
		}

	}

	/// <summary>
	/// Encapsulates a Character Set ECI, according to "Extended Channel Interpretations" 5.3.1.1
	/// of ISO 18004.
	/// 
	/// @author Sean Owen
	/// </summary>
	public abstract class CharacterSetECI
	{
		private CharacterSetECI()
		{

		}

		private static object _syncLock;

		static CharacterSetECI()
		{
			lock (_syncLock)
			{
				addSet((innerCharacterSetECI)Cp437);
				addSet((innerCharacterSetECI)ISO8859_1);
				addSet((innerCharacterSetECI)ISO8859_2);
				addSet((innerCharacterSetECI)ISO8859_3);
				addSet((innerCharacterSetECI)ISO8859_4);
				addSet((innerCharacterSetECI)ISO8859_5);
				addSet((innerCharacterSetECI)ISO8859_6);
				addSet((innerCharacterSetECI)ISO8859_7);
				addSet((innerCharacterSetECI)ISO8859_8);
				addSet((innerCharacterSetECI)ISO8859_9);
				addSet((innerCharacterSetECI)ISO8859_10);
				addSet((innerCharacterSetECI)ISO8859_11);
				addSet((innerCharacterSetECI)ISO8859_13);
				addSet((innerCharacterSetECI)ISO8859_14);
				addSet((innerCharacterSetECI)ISO8859_15);
				addSet((innerCharacterSetECI)ISO8859_16);
				addSet((innerCharacterSetECI)SJIS);
				addSet((innerCharacterSetECI)Cp1250);
				addSet((innerCharacterSetECI)Cp1251);
				addSet((innerCharacterSetECI)Cp1252);
				addSet((innerCharacterSetECI)Cp1256);
				addSet((innerCharacterSetECI)UnicodeBigUnmarked);
				addSet((innerCharacterSetECI)UTF8);
				addSet((innerCharacterSetECI)ASCII);
				addSet((innerCharacterSetECI)Big5);
				addSet((innerCharacterSetECI)GB18030);
				addSet((innerCharacterSetECI)EUC_KR);
			}
		}

		private static void addSet(innerCharacterSetECI set)
		{
			foreach (int value in set.Values)
			{
				VALUE_TO_ECI[value] = set;
			}

			foreach (string name in set.OtherEncodingNames)
			{
				NAME_TO_ECI[name] = set;
			}
		}

		private class innerCharacterSetECI : CharacterSetECI
		{
			private int[] values;
			private string[] otherEncodingNames;



			//internal Thing(int value)
			//{
			//    setup(value);
			//}

			internal innerCharacterSetECI(int value, params string[] otherEncodingNames)
			{
				setup(value, otherEncodingNames);
			}

			internal innerCharacterSetECI(int[] values, params string[] otherEncodingNames)
			{
				setup(values, otherEncodingNames);
			}

			//void setup(int value)
			//{
			//    setup(new int[] { value });
			//}

			void setup(int value, params string[] otherEncodingNames)
			{
				this.values = new int[] { value };
				this.otherEncodingNames = otherEncodingNames;
			}

			void setup(int[] values, params string[] otherEncodingNames)
			{
				this.values = values;
				this.otherEncodingNames = otherEncodingNames;
			}

			public override int Value
			{
				get { return values[0]; }
			}

			public override string name()
			{
				return otherEncodingNames[0];
			}

			public int[] Values
			{
				get { return values; }
			}

			public string[] OtherEncodingNames
			{
				get { return otherEncodingNames; }
			}
		}

		public abstract string name();


		// Enum name is a Java encoding valid for java.lang and java.io
		public static readonly CharacterSetECI Cp437 = new innerCharacterSetECI(new int[] { 0, 2 }, "Cp437", "");
		public static readonly CharacterSetECI ISO8859_1 = new innerCharacterSetECI(new int[] { 1, 3 }, "ISO-8859-1", "");

		public static readonly CharacterSetECI ISO8859_2 = new innerCharacterSetECI(4, "ISO-8859-2", "ISO8859_2");
		public static readonly CharacterSetECI ISO8859_3 = new innerCharacterSetECI(5, "ISO-8859-3", "ISO8859_3");
		public static readonly CharacterSetECI ISO8859_4 = new innerCharacterSetECI(6, "ISO-8859-4", "ISO8859_4");
		public static readonly CharacterSetECI ISO8859_5 = new innerCharacterSetECI(7, "ISO-8859-5", "ISO8859_5");
		public static readonly CharacterSetECI ISO8859_6 = new innerCharacterSetECI(8, "ISO-8859-6", "ISO8859_6");
		public static readonly CharacterSetECI ISO8859_7 = new innerCharacterSetECI(9, "ISO-8859-7", "ISO8859_7");
		public static readonly CharacterSetECI ISO8859_8 = new innerCharacterSetECI(10, "ISO-8859-8", "ISO8859_8");
		public static readonly CharacterSetECI ISO8859_9 = new innerCharacterSetECI(11, "ISO-8859-9", "ISO8859_9");
		public static readonly CharacterSetECI ISO8859_10 = new innerCharacterSetECI(12, "ISO-8859-10", "ISO8859_10");
		public static readonly CharacterSetECI ISO8859_11 = new innerCharacterSetECI(13, "ISO-8859-11", "ISO8859_11");
		public static readonly CharacterSetECI ISO8859_13 = new innerCharacterSetECI(15, "ISO-8859-13", "ISO8859_13");
		public static readonly CharacterSetECI ISO8859_14 = new innerCharacterSetECI(16, "ISO-8859-14", "ISO8859_14");
		public static readonly CharacterSetECI ISO8859_15 = new innerCharacterSetECI(17, "ISO-8859-15", "ISO8859_15");
		public static readonly CharacterSetECI ISO8859_16 = new innerCharacterSetECI(18, "ISO-8859-16", "ISO8859_16");
		public static readonly CharacterSetECI SJIS = new innerCharacterSetECI(20, "Shift_JIS", "SJIS");
		public static readonly CharacterSetECI Cp1250 = new innerCharacterSetECI(21, "windows-1250", "Cp1250");
		public static readonly CharacterSetECI Cp1251 = new innerCharacterSetECI(22, "windows-1251", "Cp1251");
		public static readonly CharacterSetECI Cp1252 = new innerCharacterSetECI(23, "windows-1252", "Cp1252");
		public static readonly CharacterSetECI Cp1256 = new innerCharacterSetECI(24, "windows-1256", "Cp1256");
		public static readonly CharacterSetECI UnicodeBigUnmarked = new innerCharacterSetECI(25, "UTF-16BE", "UnicodeBig", "UnicodeBigUnmarked");
		public static readonly CharacterSetECI UTF8 = new innerCharacterSetECI(26, "UTF-8", "");
		public static readonly CharacterSetECI ASCII = new innerCharacterSetECI(new int[] { 27, 170 }, "US-ASCII", "ASCII");
		public static readonly CharacterSetECI Big5 = new innerCharacterSetECI(28, "Big5", "Big5");
		public static readonly CharacterSetECI GB18030 = new innerCharacterSetECI(29, "GB2312", "EUC_CN", "GBK", "GB18030");
		public static readonly CharacterSetECI EUC_KR = new innerCharacterSetECI(30, "EUC-KR", "EUC_KR");

		private static readonly Dictionary<int, CharacterSetECI> VALUE_TO_ECI = new Dictionary<int, CharacterSetECI>();
		private static readonly Dictionary<string, CharacterSetECI> NAME_TO_ECI = new Dictionary<string, CharacterSetECI>();

		/// <param name="value"> character set ECI value </param>
		/// <returns> CharacterSetECI representing ECI of given value, or null if it is legal but
		///   unsupported </returns>
		/// <exception cref="IllegalArgumentException"> if ECI value is invalid </exception>
		public static CharacterSetECI getCharacterSetECIByValue(int value)
		{
			if (value < 0 || value >= 900)
			{
				throw FormatException.FormatInstance;
			}
			if (VALUE_TO_ECI.ContainsKey(value))
			{
				return VALUE_TO_ECI[value];
			}
			return null;

		}

		/// <param name="name"> character set ECI encoding name </param>
		/// <returns> CharacterSetECI representing ECI for character encoding, or null if it is legal
		///   but unsupported </returns>
		public static CharacterSetECI getCharacterSetECIByName(string name)
		{
			if (NAME_TO_ECI.ContainsKey(name))
			{
				return NAME_TO_ECI[name];
			}
			return null;
		}

		public virtual int Value { get { throw new NotImplementedException(); } }
	}
	//public static partial class EnumExtensionMethods
	//{
	//    public static int getValue(this CharacterSetECI instanceJavaToDotNetTempPropertyGetValue)
	//    {
	//        return values[0];
	//    }
	//}

	/// <summary>
	/// <p>Encapsulates the result of decoding a matrix of bits. This typically
	/// applies to 2D barcode formats. For now it contains the raw bytes obtained,
	/// as well as a String interpretation of those bytes, if applicable.</p>
	/// 
	/// @author Sean Owen
	/// </summary>
	public sealed class DecoderResult
	{

		private readonly sbyte[] rawBytes;
		private readonly string text;
		private readonly IList<sbyte[]> byteSegments;
		private readonly string ecLevel;

		public DecoderResult(sbyte[] rawBytes, string text, IList<sbyte[]> byteSegments, string ecLevel)
		{
			this.rawBytes = rawBytes;
			this.text = text;
			this.byteSegments = byteSegments;
			this.ecLevel = ecLevel;
		}

		public sbyte[] RawBytes
		{
			get
			{
				return rawBytes;
			}
		}

		public string Text
		{
			get
			{
				return text;
			}
		}

		public IList<sbyte[]> ByteSegments
		{
			get
			{
				return byteSegments;
			}
		}

		public string ECLevel
		{
			get
			{
				return ecLevel;
			}
		}

	}

	/// <summary>
	/// @author Sean Owen
	/// </summary>
	public sealed class DefaultGridSampler : GridSampler
	{

		//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET:
		//ORIGINAL LINE: public BitMatrix sampleGrid(BitMatrix image, int dimensionX, int dimensionY, float p1ToX, float p1ToY, float p2ToX, float p2ToY, float p3ToX, float p3ToY, float p4ToX, float p4ToY, float p1FromX, float p1FromY, float p2FromX, float p2FromY, float p3FromX, float p3FromY, float p4FromX, float p4FromY) throws com.google.zxing.NotFoundException
		public override BitMatrix sampleGrid(BitMatrix image, int dimensionX, int dimensionY, float p1ToX, float p1ToY, float p2ToX, float p2ToY, float p3ToX, float p3ToY, float p4ToX, float p4ToY, float p1FromX, float p1FromY, float p2FromX, float p2FromY, float p3FromX, float p3FromY, float p4FromX, float p4FromY)
		{

			PerspectiveTransform transform = PerspectiveTransform.quadrilateralToQuadrilateral(p1ToX, p1ToY, p2ToX, p2ToY, p3ToX, p3ToY, p4ToX, p4ToY, p1FromX, p1FromY, p2FromX, p2FromY, p3FromX, p3FromY, p4FromX, p4FromY);

			return sampleGrid(image, dimensionX, dimensionY, transform);
		}

		//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET:
		//ORIGINAL LINE: public BitMatrix sampleGrid(BitMatrix image, int dimensionX, int dimensionY, PerspectiveTransform transform) throws com.google.zxing.NotFoundException
		public override BitMatrix sampleGrid(BitMatrix image, int dimensionX, int dimensionY, PerspectiveTransform transform)
		{
			if (dimensionX <= 0 || dimensionY <= 0)
			{
				throw NotFoundException.NotFoundInstance;
			}
			BitMatrix bits = new BitMatrix(dimensionX, dimensionY);
			float[] points = new float[dimensionX << 1];
			for (int y = 0; y < dimensionY; y++)
			{
				int max = points.Length;
				float iValue = (float)y + 0.5f;
				for (int x = 0; x < max; x += 2)
				{
					points[x] = (float)(x >> 1) + 0.5f;
					points[x + 1] = iValue;
				}
				transform.transformPoints(points);
				// Quick check to see if points transformed to something inside the image;
				// sufficient to check the endpoints
				checkAndNudgePoints(image, points);
				try
				{
					for (int x = 0; x < max; x += 2)
					{
						if (image.get((int)points[x], (int)points[x + 1]))
						{
							// Black(-ish) pixel
							bits.set(x >> 1, y);
						}
					}
				}
				catch (System.IndexOutOfRangeException aioobe)
				{
					// This feels wrong, but, sometimes if the finder patterns are misidentified, the resulting
					// transform gets "twisted" such that it maps a straight line of points to a set of points
					// whose endpoints are in bounds, but others are not. There is probably some mathematical
					// way to detect this about the transformation that I don't know yet.
					// This results in an ugly runtime exception despite our clever checks above -- can't have
					// that. We could check each point's coordinates but that feels duplicative. We settle for
					// catching and wrapping ArrayIndexOutOfBoundsException.
					throw NotFoundException.NotFoundInstance;
				}
			}
			return bits;
		}

	}

	/// <summary>
	/// <p>Encapsulates the result of detecting a barcode in an image. This includes the raw
	/// matrix of black/white pixels corresponding to the barcode, and possibly points of interest
	/// in the image, like the location of finder patterns or corners of the barcode in the image.</p>
	/// 
	/// @author Sean Owen
	/// </summary>
	public class DetectorResult
	{

		private readonly BitMatrix bits;
		private readonly ResultPoint[] points;

		public DetectorResult(BitMatrix bits, ResultPoint[] points)
		{
			this.bits = bits;
			this.points = points;
		}

		public BitMatrix Bits
		{
			get
			{
				return bits;
			}
		}

		public ResultPoint[] Points
		{
			get
			{
				return points;
			}
		}

	}

	/// <summary>
	/// This Binarizer implementation uses the old ZXing global histogram approach. It is suitable
	/// for low-end mobile devices which don't have enough CPU or memory to use a local thresholding
	/// algorithm. However, because it picks a global black point, it cannot handle difficult shadows
	/// and gradients.
	/// 
	/// Faster mobile devices and all desktop applications should probably use HybridBinarizer instead.
	/// 
	/// @author dswitkin@google.com (Daniel Switkin)
	/// @author Sean Owen
	/// </summary>
	public class GlobalHistogramBinarizer : Binarizer
	{

		private const int LUMINANCE_BITS = 5;
		private static readonly int LUMINANCE_SHIFT = 8 - LUMINANCE_BITS;
		private static readonly int LUMINANCE_BUCKETS = 1 << LUMINANCE_BITS;
		private static readonly sbyte[] EMPTY = new sbyte[0];

		private sbyte[] luminances;
		private readonly int[] buckets;

		public GlobalHistogramBinarizer(LuminanceSource source)
			: base(source)
		{
			luminances = EMPTY;
			buckets = new int[LUMINANCE_BUCKETS];
		}

		// Applies simple sharpening to the row data to improve performance of the 1D Readers.
		//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET:
		//ORIGINAL LINE: public BitArray getBlackRow(int y, BitArray row) throws com.google.zxing.NotFoundException
		public override BitArray getBlackRow(int y, BitArray row)
		{
			LuminanceSource source = LuminanceSource;
			int width = source.Width;
			if (row == null || row.Size < width)
			{
				row = new BitArray(width);
			}
			else
			{
				//row.SetAll(false);
				row.clear();
			}

			initArrays(width);
			sbyte[] localLuminances = source.getRow(y, luminances);
			int[] localBuckets = buckets;
			for (int x = 0; x < width; x++)
			{
				int pixel = localLuminances[x] & 0xff;
				localBuckets[pixel >> LUMINANCE_SHIFT]++;
			}
			int blackPoint = estimateBlackPoint(localBuckets);

			int left = localLuminances[0] & 0xff;
			int center = localLuminances[1] & 0xff;
			for (int x = 1; x < width - 1; x++)
			{
				int right = localLuminances[x + 1] & 0xff;
				// A simple -1 4 -1 box filter with a weight of 2.
				int luminance = ((center << 2) - left - right) >> 1;
				if (luminance < blackPoint)
				{
					//row.Set(x, true);
					row.set(x);
				}
				left = center;
				center = right;
			}
			return row;
		}

		// Does not sharpen the data, as this call is intended to only be used by 2D Readers.
		//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET:
		//ORIGINAL LINE: public BitMatrix getBlackMatrix() throws com.google.zxing.NotFoundException
		public override BitMatrix BlackMatrix
		{
			get
			{
				LuminanceSource source = LuminanceSource;
				int width = source.Width;
				int height = source.Height;
				BitMatrix matrix = new BitMatrix(width, height);

				// Quickly calculates the histogram by sampling four rows from the image. This proved to be
				// more robust on the blackbox tests than sampling a diagonal as we used to do.
				initArrays(width);
				int[] localBuckets = buckets;
				for (int y = 1; y < 5; y++)
				{
					int row = height * y / 5;
					sbyte[] localLuminances1 = source.getRow(row, luminances);
					int right = (width << 2) / 5;
					for (int x = width / 5; x < right; x++)
					{
						int pixel = localLuminances1[x] & 0xff;
						localBuckets[pixel >> LUMINANCE_SHIFT]++;
					}
				}
				int blackPoint = estimateBlackPoint(localBuckets);

				// We delay reading the entire image luminance until the black point estimation succeeds.
				// Although we end up reading four rows twice, it is consistent with our motto of
				// "fail quickly" which is necessary for continuous scanning.
				sbyte[] localLuminances = source.Matrix;
				for (int y = 0; y < height; y++)
				{
					int offset = y * width;
					for (int x = 0; x < width; x++)
					{
						int pixel = localLuminances[offset + x] & 0xff;
						if (pixel < blackPoint)
						{
							matrix.set(x, y);
						}
					}
				}

				return matrix;
			}
		}

		public override Binarizer createBinarizer(LuminanceSource source)
		{
			return new GlobalHistogramBinarizer(source);
		}

		private void initArrays(int luminanceSize)
		{
			if (luminances.Length < luminanceSize)
			{
				luminances = new sbyte[luminanceSize];
			}
			for (int x = 0; x < LUMINANCE_BUCKETS; x++)
			{
				buckets[x] = 0;
			}
		}

		//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET:
		//ORIGINAL LINE: private static int estimateBlackPoint(int[] buckets) throws com.google.zxing.NotFoundException
		private static int estimateBlackPoint(int[] buckets)
		{
			// Find the tallest peak in the histogram.
			int numBuckets = buckets.Length;
			int maxBucketCount = 0;
			int firstPeak = 0;
			int firstPeakSize = 0;
			for (int x = 0; x < numBuckets; x++)
			{
				if (buckets[x] > firstPeakSize)
				{
					firstPeak = x;
					firstPeakSize = buckets[x];
				}
				if (buckets[x] > maxBucketCount)
				{
					maxBucketCount = buckets[x];
				}
			}

			// Find the second-tallest peak which is somewhat far from the tallest peak.
			int secondPeak = 0;
			int secondPeakScore = 0;
			for (int x = 0; x < numBuckets; x++)
			{
				int distanceToBiggest = x - firstPeak;
				// Encourage more distant second peaks by multiplying by square of distance.
				int score = buckets[x] * distanceToBiggest * distanceToBiggest;
				if (score > secondPeakScore)
				{
					secondPeak = x;
					secondPeakScore = score;
				}
			}

			// Make sure firstPeak corresponds to the black peak.
			if (firstPeak > secondPeak)
			{
				int temp = firstPeak;
				firstPeak = secondPeak;
				secondPeak = temp;
			}

			// If there is too little contrast in the image to pick a meaningful black point, throw rather
			// than waste time trying to decode the image, and risk false positives.
			if (secondPeak - firstPeak <= numBuckets >> 4)
			{
				throw NotFoundException.NotFoundInstance;
			}

			// Find a valley between them that is low and closer to the white peak.
			int bestValley = secondPeak - 1;
			int bestValleyScore = -1;
			for (int x = secondPeak - 1; x > firstPeak; x--)
			{
				int fromFirst = x - firstPeak;
				int score = fromFirst * fromFirst * (secondPeak - x) * (maxBucketCount - buckets[x]);
				if (score > bestValleyScore)
				{
					bestValley = x;
					bestValleyScore = score;
				}
			}

			return bestValley << LUMINANCE_SHIFT;
		}

	}

	/// <summary>
	/// Implementations of this class can, given locations of finder patterns for a QR code in an
	/// image, sample the right points in the image to reconstruct the QR code, accounting for
	/// perspective distortion. It is abstracted since it is relatively expensive and should be allowed
	/// to take advantage of platform-specific optimized implementations, like Sun's Java Advanced
	/// Imaging library, but which may not be available in other environments such as J2ME, and vice
	/// versa.
	/// 
	/// The implementation used can be controlled by calling <seealso cref="#setGridSampler(GridSampler)"/>
	/// with an instance of a class which implements this interface.
	/// 
	/// @author Sean Owen
	/// </summary>
	public abstract class GridSampler
	{

		private static GridSampler gridSampler = new DefaultGridSampler();

		/// <summary>
		/// Sets the implementation of GridSampler used by the library. One global
		/// instance is stored, which may sound problematic. But, the implementation provided
		/// ought to be appropriate for the entire platform, and all uses of this library
		/// in the whole lifetime of the JVM. For instance, an Android activity can swap in
		/// an implementation that takes advantage of native platform libraries.
		/// </summary>
		/// <param name="newGridSampler"> The platform-specific object to install. </param>
		public static GridSampler GridSampler2
		{
			set
			{
				gridSampler = value;
			}
		}

		/// <returns> the current implementation of GridSampler </returns>
		public static GridSampler Instance
		{
			get
			{
				return gridSampler;
			}
		}

		/// <summary>
		/// Samples an image for a rectangular matrix of bits of the given dimension. </summary>
		/// <param name="image"> image to sample </param>
		/// <param name="dimensionX"> width of <seealso cref="BitMatrix"/> to sample from image </param>
		/// <param name="dimensionY"> height of <seealso cref="BitMatrix"/> to sample from image </param>
		/// <returns> <seealso cref="BitMatrix"/> representing a grid of points sampled from the image within a region
		///   defined by the "from" parameters </returns>
		/// <exception cref="NotFoundException"> if image can't be sampled, for example, if the transformation defined
		///   by the given points is invalid or results in sampling outside the image boundaries </exception>
		//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET:
		//ORIGINAL LINE: public abstract BitMatrix sampleGrid(BitMatrix image, int dimensionX, int dimensionY, float p1ToX, float p1ToY, float p2ToX, float p2ToY, float p3ToX, float p3ToY, float p4ToX, float p4ToY, float p1FromX, float p1FromY, float p2FromX, float p2FromY, float p3FromX, float p3FromY, float p4FromX, float p4FromY) throws com.google.zxing.NotFoundException;
		public abstract BitMatrix sampleGrid(BitMatrix image, int dimensionX, int dimensionY, float p1ToX, float p1ToY, float p2ToX, float p2ToY, float p3ToX, float p3ToY, float p4ToX, float p4ToY, float p1FromX, float p1FromY, float p2FromX, float p2FromY, float p3FromX, float p3FromY, float p4FromX, float p4FromY);

		//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET:
		//ORIGINAL LINE: public abstract BitMatrix sampleGrid(BitMatrix image, int dimensionX, int dimensionY, PerspectiveTransform transform) throws com.google.zxing.NotFoundException;
		public abstract BitMatrix sampleGrid(BitMatrix image, int dimensionX, int dimensionY, PerspectiveTransform transform);

		/// <summary>
		/// <p>Checks a set of points that have been transformed to sample points on an image against
		/// the image's dimensions to see if the point are even within the image.</p>
		/// 
		/// <p>This method will actually "nudge" the endpoints back onto the image if they are found to be
		/// barely (less than 1 pixel) off the image. This accounts for imperfect detection of finder
		/// patterns in an image where the QR Code runs all the way to the image border.</p>
		/// 
		/// <p>For efficiency, the method will check points from either end of the line until one is found
		/// to be within the image. Because the set of points are assumed to be linear, this is valid.</p>
		/// </summary>
		/// <param name="image"> image into which the points should map </param>
		/// <param name="points"> actual points in x1,y1,...,xn,yn form </param>
		/// <exception cref="NotFoundException"> if an endpoint is lies outside the image boundaries </exception>
		//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET:
		//ORIGINAL LINE: protected static void checkAndNudgePoints(BitMatrix image, float[] points) throws com.google.zxing.NotFoundException
		protected internal static void checkAndNudgePoints(BitMatrix image, float[] points)
		{
			int width = image.Width;
			int height = image.Height;
			// Check and nudge points from start until we see some that are OK:
			bool nudged = true;
			for (int offset = 0; offset < points.Length && nudged; offset += 2)
			{
				int x = (int)points[offset];
				int y = (int)points[offset + 1];
				if (x < -1 || x > width || y < -1 || y > height)
				{
					throw NotFoundException.NotFoundInstance;
				}
				nudged = false;
				if (x == -1)
				{
					points[offset] = 0.0f;
					nudged = true;
				}
				else if (x == width)
				{
					points[offset] = width - 1;
					nudged = true;
				}
				if (y == -1)
				{
					points[offset + 1] = 0.0f;
					nudged = true;
				}
				else if (y == height)
				{
					points[offset + 1] = height - 1;
					nudged = true;
				}
			}
			// Check and nudge points from end:
			nudged = true;
			for (int offset = points.Length - 2; offset >= 0 && nudged; offset -= 2)
			{
				int x = (int)points[offset];
				int y = (int)points[offset + 1];
				if (x < -1 || x > width || y < -1 || y > height)
				{
					throw NotFoundException.NotFoundInstance;
				}
				nudged = false;
				if (x == -1)
				{
					points[offset] = 0.0f;
					nudged = true;
				}
				else if (x == width)
				{
					points[offset] = width - 1;
					nudged = true;
				}
				if (y == -1)
				{
					points[offset + 1] = 0.0f;
					nudged = true;
				}
				else if (y == height)
				{
					points[offset + 1] = height - 1;
					nudged = true;
				}
			}
		}

	}

	/// <summary>
	/// This class implements a local thresholding algorithm, which while slower than the
	/// GlobalHistogramBinarizer, is fairly efficient for what it does. It is designed for
	/// high frequency images of barcodes with black data on white backgrounds. For this application,
	/// it does a much better job than a global blackpoint with severe shadows and gradients.
	/// However it tends to produce artifacts on lower frequency images and is therefore not
	/// a good general purpose binarizer for uses outside ZXing.
	/// 
	/// This class extends GlobalHistogramBinarizer, using the older histogram approach for 1D readers,
	/// and the newer local approach for 2D readers. 1D decoding using a per-row histogram is already
	/// inherently local, and only fails for horizontal gradients. We can revisit that problem later,
	/// but for now it was not a win to use local blocks for 1D.
	/// 
	/// This Binarizer is the default for the unit tests and the recommended class for library users.
	/// 
	/// @author dswitkin@google.com (Daniel Switkin)
	/// </summary>
	public sealed class HybridBinarizer : GlobalHistogramBinarizer
	{

		// This class uses 5x5 blocks to compute local luminance, where each block is 8x8 pixels.
		// So this is the smallest dimension in each axis we can accept.
		private const int BLOCK_SIZE_POWER = 3;
		private static readonly int BLOCK_SIZE = 1 << BLOCK_SIZE_POWER; // ...0100...00
		private static readonly int BLOCK_SIZE_MASK = BLOCK_SIZE - 1; // ...0011...11
		private static readonly int MINIMUM_DIMENSION = BLOCK_SIZE * 5;
		private const int MIN_DYNAMIC_RANGE = 24;

		private BitMatrix matrix;

		public HybridBinarizer(LuminanceSource source)
			: base(source)
		{
		}

		/// <summary>
		/// Calculates the final BitMatrix once for all requests. This could be called once from the
		/// constructor instead, but there are some advantages to doing it lazily, such as making
		/// profiling easier, and not doing heavy lifting when callers don't expect it.
		/// </summary>
		//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET:
		//ORIGINAL LINE: public BitMatrix getBlackMatrix() throws com.google.zxing.NotFoundException
		public override BitMatrix BlackMatrix
		{
			get
			{
				if (matrix != null)
				{
					return matrix;
				}
				LuminanceSource source = LuminanceSource;
				int width = source.Width;
				int height = source.Height;
				if (width >= MINIMUM_DIMENSION && height >= MINIMUM_DIMENSION)
				{
					sbyte[] luminances = source.Matrix;
					int subWidth = width >> BLOCK_SIZE_POWER;
					if ((width & BLOCK_SIZE_MASK) != 0)
					{
						subWidth++;
					}
					int subHeight = height >> BLOCK_SIZE_POWER;
					if ((height & BLOCK_SIZE_MASK) != 0)
					{
						subHeight++;
					}
					int[][] blackPoints = calculateBlackPoints(luminances, subWidth, subHeight, width, height);

					BitMatrix newMatrix = new BitMatrix(width, height);
					calculateThresholdForBlock(luminances, subWidth, subHeight, width, height, blackPoints, newMatrix);
					matrix = newMatrix;
				}
				else
				{
					// If the image is too small, fall back to the global histogram approach.
					matrix = base.BlackMatrix;
				}
				return matrix;
			}
		}

		public override Binarizer createBinarizer(LuminanceSource source)
		{
			return new HybridBinarizer(source);
		}

		/// <summary>
		/// For each block in the image, calculate the average black point using a 5x5 grid
		/// of the blocks around it. Also handles the corner cases (fractional blocks are computed based
		/// on the last pixels in the row/column which are also used in the previous block).
		/// </summary>
		private static void calculateThresholdForBlock(sbyte[] luminances, int subWidth, int subHeight, int width, int height, int[][] blackPoints, BitMatrix matrix)
		{
			for (int y = 0; y < subHeight; y++)
			{
				int yoffset = y << BLOCK_SIZE_POWER;
				int maxYOffset = height - BLOCK_SIZE;
				if (yoffset > maxYOffset)
				{
					yoffset = maxYOffset;
				}
				for (int x = 0; x < subWidth; x++)
				{
					int xoffset = x << BLOCK_SIZE_POWER;
					int maxXOffset = width - BLOCK_SIZE;
					if (xoffset > maxXOffset)
					{
						xoffset = maxXOffset;
					}
					int left = cap(x, 2, subWidth - 3);
					int top = cap(y, 2, subHeight - 3);
					int sum = 0;
					for (int z = -2; z <= 2; z++)
					{
						int[] blackRow = blackPoints[top + z];
						sum += blackRow[left - 2] + blackRow[left - 1] + blackRow[left] + blackRow[left + 1] + blackRow[left + 2];
					}
					int average = sum / 25;
					thresholdBlock(luminances, xoffset, yoffset, average, width, matrix);
				}
			}
		}

		private static int cap(int value, int min, int max)
		{
			return value < min ? min : value > max ? max : value;
		}

		/// <summary>
		/// Applies a single threshold to a block of pixels.
		/// </summary>
		private static void thresholdBlock(sbyte[] luminances, int xoffset, int yoffset, int threshold, int stride, BitMatrix matrix)
		{
			for (int y = 0, offset = yoffset * stride + xoffset; y < BLOCK_SIZE; y++, offset += stride)
			{
				for (int x = 0; x < BLOCK_SIZE; x++)
				{
					// Comparison needs to be <= so that black == 0 pixels are black even if the threshold is 0.
					if ((luminances[offset + x] & 0xFF) <= threshold)
					{
						matrix.set(xoffset + x, yoffset + y);
					}
				}
			}
		}

		/// <summary>
		/// Calculates a single black point for each block of pixels and saves it away.
		/// See the following thread for a discussion of this algorithm:
		///  http://groups.google.com/group/zxing/browse_thread/thread/d06efa2c35a7ddc0
		/// </summary>
		private static int[][] calculateBlackPoints(sbyte[] luminances, int subWidth, int subHeight, int width, int height)
		{
			//JAVA TO C# CONVERTER NOTE: The following call to the 'RectangularArrays' helper class reproduces the rectangular array initialization that is automatic in Java:
			//ORIGINAL LINE: int[][] blackPoints = new int[subHeight][subWidth];
			int[][] blackPoints = RectangularArrays.ReturnRectangularIntArray(subHeight, subWidth);
			for (int y = 0; y < subHeight; y++)
			{
				int yoffset = y << BLOCK_SIZE_POWER;
				int maxYOffset = height - BLOCK_SIZE;
				if (yoffset > maxYOffset)
				{
					yoffset = maxYOffset;
				}
				for (int x = 0; x < subWidth; x++)
				{
					int xoffset = x << BLOCK_SIZE_POWER;
					int maxXOffset = width - BLOCK_SIZE;
					if (xoffset > maxXOffset)
					{
						xoffset = maxXOffset;
					}
					int sum = 0;
					int min = 0xFF;
					int max = 0;
					for (int yy = 0, offset = yoffset * width + xoffset; yy < BLOCK_SIZE; yy++, offset += width)
					{
						for (int xx = 0; xx < BLOCK_SIZE; xx++)
						{
							int pixel = luminances[offset + xx] & 0xFF;
							sum += pixel;
							// still looking for good contrast
							if (pixel < min)
							{
								min = pixel;
							}
							if (pixel > max)
							{
								max = pixel;
							}
						}
						// short-circuit min/max tests once dynamic range is met
						if (max - min > MIN_DYNAMIC_RANGE)
						{
							// finish the rest of the rows quickly
							for (yy++, offset += width; yy < BLOCK_SIZE; yy++, offset += width)
							{
								for (int xx = 0; xx < BLOCK_SIZE; xx++)
								{
									sum += luminances[offset + xx] & 0xFF;
								}
							}
						}
					}

					// The default estimate is the average of the values in the block.
					int average = sum >> (BLOCK_SIZE_POWER * 2);
					if (max - min <= MIN_DYNAMIC_RANGE)
					{
						// If variation within the block is low, assume this is a block with only light or only
						// dark pixels. In that case we do not want to use the average, as it would divide this
						// low contrast area into black and white pixels, essentially creating data out of noise.
						//
						// The default assumption is that the block is light/background. Since no estimate for
						// the level of dark pixels exists locally, use half the min for the block.
						average = min >> 1;

						if (y > 0 && x > 0)
						{
							// Correct the "white background" assumption for blocks that have neighbors by comparing
							// the pixels in this block to the previously calculated black points. This is based on
							// the fact that dark barcode symbology is always surrounded by some amount of light
							// background for which reasonable black point estimates were made. The bp estimated at
							// the boundaries is used for the interior.

							// The (min < bp) is arbitrary but works better than other heuristics that were tried.
							int averageNeighborBlackPoint = (blackPoints[y - 1][x] + (2 * blackPoints[y][x - 1]) + blackPoints[y - 1][x - 1]) >> 2;
							if (min < averageNeighborBlackPoint)
							{
								average = averageNeighborBlackPoint;
							}
						}
					}
					blackPoints[y][x] = average;
				}
			}
			return blackPoints;
		}

	}

	/// <summary>
	/// <p>This class implements a perspective transform in two dimensions. Given four source and four
	/// destination points, it will compute the transformation implied between them. The code is based
	/// directly upon section 3.4.2 of George Wolberg's "Digital Image Warping"; see pages 54-56.</p>
	/// 
	/// @author Sean Owen
	/// </summary>
	public sealed class PerspectiveTransform
	{

		private readonly float a11;
		private readonly float a12;
		private readonly float a13;
		private readonly float a21;
		private readonly float a22;
		private readonly float a23;
		private readonly float a31;
		private readonly float a32;
		private readonly float a33;

		private PerspectiveTransform(float a11, float a21, float a31, float a12, float a22, float a32, float a13, float a23, float a33)
		{
			this.a11 = a11;
			this.a12 = a12;
			this.a13 = a13;
			this.a21 = a21;
			this.a22 = a22;
			this.a23 = a23;
			this.a31 = a31;
			this.a32 = a32;
			this.a33 = a33;
		}

		public static PerspectiveTransform quadrilateralToQuadrilateral(float x0, float y0, float x1, float y1, float x2, float y2, float x3, float y3, float x0p, float y0p, float x1p, float y1p, float x2p, float y2p, float x3p, float y3p)
		{

			PerspectiveTransform qToS = quadrilateralToSquare(x0, y0, x1, y1, x2, y2, x3, y3);
			PerspectiveTransform sToQ = squareToQuadrilateral(x0p, y0p, x1p, y1p, x2p, y2p, x3p, y3p);
			return sToQ.times(qToS);
		}

		public void transformPoints(float[] points)
		{
			int max = points.Length;
			float a11 = this.a11;
			float a12 = this.a12;
			float a13 = this.a13;
			float a21 = this.a21;
			float a22 = this.a22;
			float a23 = this.a23;
			float a31 = this.a31;
			float a32 = this.a32;
			float a33 = this.a33;
			for (int i = 0; i < max; i += 2)
			{
				float x = points[i];
				float y = points[i + 1];
				float denominator = a13 * x + a23 * y + a33;
				points[i] = (a11 * x + a21 * y + a31) / denominator;
				points[i + 1] = (a12 * x + a22 * y + a32) / denominator;
			}
		}

		/// <summary>
		/// Convenience method, not optimized for performance. </summary>
		public void transformPoints(float[] xValues, float[] yValues)
		{
			int n = xValues.Length;
			for (int i = 0; i < n; i++)
			{
				float x = xValues[i];
				float y = yValues[i];
				float denominator = a13 * x + a23 * y + a33;
				xValues[i] = (a11 * x + a21 * y + a31) / denominator;
				yValues[i] = (a12 * x + a22 * y + a32) / denominator;
			}
		}

		public static PerspectiveTransform squareToQuadrilateral(float x0, float y0, float x1, float y1, float x2, float y2, float x3, float y3)
		{
			float dx3 = x0 - x1 + x2 - x3;
			float dy3 = y0 - y1 + y2 - y3;
			if (dx3 == 0.0f && dy3 == 0.0f)
			{
				// Affine
				return new PerspectiveTransform(x1 - x0, x2 - x1, x0, y1 - y0, y2 - y1, y0, 0.0f, 0.0f, 1.0f);
			}
			else
			{
				float dx1 = x1 - x2;
				float dx2 = x3 - x2;
				float dy1 = y1 - y2;
				float dy2 = y3 - y2;
				float denominator = dx1 * dy2 - dx2 * dy1;
				float a13 = (dx3 * dy2 - dx2 * dy3) / denominator;
				float a23 = (dx1 * dy3 - dx3 * dy1) / denominator;
				return new PerspectiveTransform(x1 - x0 + a13 * x1, x3 - x0 + a23 * x3, x0, y1 - y0 + a13 * y1, y3 - y0 + a23 * y3, y0, a13, a23, 1.0f);
			}
		}

		public static PerspectiveTransform quadrilateralToSquare(float x0, float y0, float x1, float y1, float x2, float y2, float x3, float y3)
		{
			// Here, the adjoint serves as the inverse:
			return squareToQuadrilateral(x0, y0, x1, y1, x2, y2, x3, y3).buildAdjoint();
		}

		internal PerspectiveTransform buildAdjoint()
		{
			// Adjoint is the transpose of the cofactor matrix:
			return new PerspectiveTransform(a22 * a33 - a23 * a32, a23 * a31 - a21 * a33, a21 * a32 - a22 * a31, a13 * a32 - a12 * a33, a11 * a33 - a13 * a31, a12 * a31 - a11 * a32, a12 * a23 - a13 * a22, a13 * a21 - a11 * a23, a11 * a22 - a12 * a21);
		}

		internal PerspectiveTransform times(PerspectiveTransform other)
		{
			return new PerspectiveTransform(a11 * other.a11 + a21 * other.a12 + a31 * other.a13, a11 * other.a21 + a21 * other.a22 + a31 * other.a23, a11 * other.a31 + a21 * other.a32 + a31 * other.a33, a12 * other.a11 + a22 * other.a12 + a32 * other.a13, a12 * other.a21 + a22 * other.a22 + a32 * other.a23, a12 * other.a31 + a22 * other.a32 + a32 * other.a33, a13 * other.a11 + a23 * other.a12 + a33 * other.a13, a13 * other.a21 + a23 * other.a22 + a33 * other.a23, a13 * other.a31 + a23 * other.a32 + a33 * other.a33);

		}

	}

	/// <summary>
	/// <p>A somewhat generic detector that looks for a barcode-like rectangular region within an image.
	/// It looks within a mostly white region of an image for a region of black and white, but mostly
	/// black. It returns the four corners of the region, as best it can determine.</p>
	/// 
	/// @author Sean Owen
	/// </summary>
	public sealed class MonochromeRectangleDetector
	{

		private const int MAX_MODULES = 32;

		private readonly BitMatrix image;

		public MonochromeRectangleDetector(BitMatrix image)
		{
			this.image = image;
		}

		/// <summary>
		/// <p>Detects a rectangular region of black and white -- mostly black -- with a region of mostly
		/// white, in an image.</p>
		/// </summary>
		/// <returns> <seealso cref="ResultPoint"/>[] describing the corners of the rectangular region. The first and
		///  last points are opposed on the diagonal, as are the second and third. The first point will be
		///  the topmost point and the last, the bottommost. The second point will be leftmost and the
		///  third, the rightmost </returns>
		/// <exception cref="NotFoundException"> if no Data Matrix Code can be found </exception>
		//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET:
		//ORIGINAL LINE: public com.google.zxing.ResultPoint[] detect() throws com.google.zxing.NotFoundException
		public ResultPoint[] detect()
		{
			int height = image.Height;
			int width = image.Width;
			int halfHeight = height >> 1;
			int halfWidth = width >> 1;
			int deltaY = Math.Max(1, height / (MAX_MODULES << 3));
			int deltaX = Math.Max(1, width / (MAX_MODULES << 3));

			int top = 0;
			int bottom = height;
			int left = 0;
			int right = width;
			ResultPoint pointA = findCornerFromCenter(halfWidth, 0, left, right, halfHeight, -deltaY, top, bottom, halfWidth >> 1);
			top = (int)pointA.Y - 1;
			ResultPoint pointB = findCornerFromCenter(halfWidth, -deltaX, left, right, halfHeight, 0, top, bottom, halfHeight >> 1);
			left = (int)pointB.X - 1;
			ResultPoint pointC = findCornerFromCenter(halfWidth, deltaX, left, right, halfHeight, 0, top, bottom, halfHeight >> 1);
			right = (int)pointC.X + 1;
			ResultPoint pointD = findCornerFromCenter(halfWidth, 0, left, right, halfHeight, deltaY, top, bottom, halfWidth >> 1);
			bottom = (int)pointD.Y + 1;

			// Go try to find point A again with better information -- might have been off at first.
			pointA = findCornerFromCenter(halfWidth, 0, left, right, halfHeight, -deltaY, top, bottom, halfWidth >> 2);

			return new ResultPoint[] { pointA, pointB, pointC, pointD };
		}

		/// <summary>
		/// Attempts to locate a corner of the barcode by scanning up, down, left or right from a center
		/// point which should be within the barcode.
		/// </summary>
		/// <param name="centerX"> center's x component (horizontal) </param>
		/// <param name="deltaX"> same as deltaY but change in x per step instead </param>
		/// <param name="left"> minimum value of x </param>
		/// <param name="right"> maximum value of x </param>
		/// <param name="centerY"> center's y component (vertical) </param>
		/// <param name="deltaY"> change in y per step. If scanning up this is negative; down, positive;
		///  left or right, 0 </param>
		/// <param name="top"> minimum value of y to search through (meaningless when di == 0) </param>
		/// <param name="bottom"> maximum value of y </param>
		/// <param name="maxWhiteRun"> maximum run of white pixels that can still be considered to be within
		///  the barcode </param>
		/// <returns> a <seealso cref="com.google.zxing.ResultPoint"/> encapsulating the corner that was found </returns>
		/// <exception cref="NotFoundException"> if such a point cannot be found </exception>
		//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET:
		//ORIGINAL LINE: private com.google.zxing.ResultPoint findCornerFromCenter(int centerX, int deltaX, int left, int right, int centerY, int deltaY, int top, int bottom, int maxWhiteRun) throws com.google.zxing.NotFoundException
		private ResultPoint findCornerFromCenter(int centerX, int deltaX, int left, int right, int centerY, int deltaY, int top, int bottom, int maxWhiteRun)
		{
			int[] lastRange = null;
			for (int y = centerY, x = centerX; y < bottom && y >= top && x < right && x >= left; y += deltaY, x += deltaX)
			{
				int[] range;
				if (deltaX == 0)
				{
					// horizontal slices, up and down
					range = blackWhiteRange(y, maxWhiteRun, left, right, true);
				}
				else
				{
					// vertical slices, left and right
					range = blackWhiteRange(x, maxWhiteRun, top, bottom, false);
				}
				if (range == null)
				{
					if (lastRange == null)
					{
						throw NotFoundException.NotFoundInstance;
					}
					// lastRange was found
					if (deltaX == 0)
					{
						int lastY = y - deltaY;
						if (lastRange[0] < centerX)
						{
							if (lastRange[1] > centerX)
							{
								// straddle, choose one or the other based on direction
								return new ResultPoint(deltaY > 0 ? lastRange[0] : lastRange[1], lastY);
							}
							return new ResultPoint(lastRange[0], lastY);
						}
						else
						{
							return new ResultPoint(lastRange[1], lastY);
						}
					}
					else
					{
						int lastX = x - deltaX;
						if (lastRange[0] < centerY)
						{
							if (lastRange[1] > centerY)
							{
								return new ResultPoint(lastX, deltaX < 0 ? lastRange[0] : lastRange[1]);
							}
							return new ResultPoint(lastX, lastRange[0]);
						}
						else
						{
							return new ResultPoint(lastX, lastRange[1]);
						}
					}
				}
				lastRange = range;
			}
			throw NotFoundException.NotFoundInstance;
		}

		/// <summary>
		/// Computes the start and end of a region of pixels, either horizontally or vertically, that could
		/// be part of a Data Matrix barcode.
		/// </summary>
		/// <param name="fixedDimension"> if scanning horizontally, this is the row (the fixed vertical location)
		///  where we are scanning. If scanning vertically it's the column, the fixed horizontal location </param>
		/// <param name="maxWhiteRun"> largest run of white pixels that can still be considered part of the
		///  barcode region </param>
		/// <param name="minDim"> minimum pixel location, horizontally or vertically, to consider </param>
		/// <param name="maxDim"> maximum pixel location, horizontally or vertically, to consider </param>
		/// <param name="horizontal"> if true, we're scanning left-right, instead of up-down </param>
		/// <returns> int[] with start and end of found range, or null if no such range is found
		///  (e.g. only white was found) </returns>
		private int[] blackWhiteRange(int fixedDimension, int maxWhiteRun, int minDim, int maxDim, bool horizontal)
		{

			int center = (minDim + maxDim) >> 1;

			// Scan left/up first
			int start = center;
			while (start >= minDim)
			{
				if (horizontal ? image.get(start, fixedDimension) : image.get(fixedDimension, start))
				{
					start--;
				}
				else
				{
					int whiteRunStart = start;
					do
					{
						start--;
					} while (start >= minDim && !(horizontal ? image.get(start, fixedDimension) : image.get(fixedDimension, start)));
					int whiteRunSize = whiteRunStart - start;
					if (start < minDim || whiteRunSize > maxWhiteRun)
					{
						start = whiteRunStart;
						break;
					}
				}
			}
			start++;

			// Then try right/down
			int end = center;
			while (end < maxDim)
			{
				if (horizontal ? image.get(end, fixedDimension) : image.get(fixedDimension, end))
				{
					end++;
				}
				else
				{
					int whiteRunStart = end;
					do
					{
						end++;
					} while (end < maxDim && !(horizontal ? image.get(end, fixedDimension) : image.get(fixedDimension, end)));
					int whiteRunSize = end - whiteRunStart;
					if (end >= maxDim || whiteRunSize > maxWhiteRun)
					{
						end = whiteRunStart;
						break;
					}
				}
			}
			end--;

			return end > start ? new int[] { start, end } : null;
		}

	}

	/// <summary>
	/// <p>Implements Reed-Solomon decoding, as the name implies.</p>
	/// 
	/// <p>The algorithm will not be explained here, but the following references were helpful
	/// in creating this implementation:</p>
	/// 
	/// <ul>
	/// <li>Bruce Maggs.
	/// <a href="http://www.cs.cmu.edu/afs/cs.cmu.edu/project/pscico-guyb/realworld/www/rs_decode.ps">
	/// "Decoding Reed-Solomon Codes"</a> (see discussion of Forney's Formula)</li>
	/// <li>J.I. Hall. <a href="www.mth.msu.edu/~jhall/classes/codenotes/GRS.pdf">
	/// "Chapter 5. Generalized Reed-Solomon Codes"</a>
	/// (see discussion of Euclidean algorithm)</li>
	/// </ul>
	/// 
	/// <p>Much credit is due to William Rucklidge since portions of this code are an indirect
	/// port of his C++ Reed-Solomon implementation.</p>
	/// 
	/// @author Sean Owen
	/// @author William Rucklidge
	/// @author sanfordsquires
	/// </summary>
	public sealed class ReedSolomonDecoder
	{

		private readonly GenericGF field;

		public ReedSolomonDecoder(GenericGF field)
		{
			this.field = field;
		}

		/// <summary>
		/// <p>Decodes given set of received codewords, which include both data and error-correction
		/// codewords. Really, this means it uses Reed-Solomon to detect and correct errors, in-place,
		/// in the input.</p>
		/// </summary>
		/// <param name="received"> data and error-correction codewords </param>
		/// <param name="twoS"> number of error-correction codewords available </param>
		/// <exception cref="ReedSolomonException"> if decoding fails for any reason </exception>
		//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET:
		//ORIGINAL LINE: public void decode(int[] received, int twoS) throws ReedSolomonException
		public void decode(int[] received, int twoS)
		{
			GenericGFPoly poly = new GenericGFPoly(field, received);
			int[] syndromeCoefficients = new int[twoS];
			bool dataMatrix = field.Equals(GenericGF.DATA_MATRIX_FIELD_256);
			bool noError = true;
			for (int i = 0; i < twoS; i++)
			{
				// Thanks to sanfordsquires for this fix:
				int eval = poly.evaluateAt(field.exp(dataMatrix ? i + 1 : i));
				syndromeCoefficients[syndromeCoefficients.Length - 1 - i] = eval;
				if (eval != 0)
				{
					noError = false;
				}
			}
			if (noError)
			{
				return;
			}
			GenericGFPoly syndrome = new GenericGFPoly(field, syndromeCoefficients);
			GenericGFPoly[] sigmaOmega = runEuclideanAlgorithm(field.buildMonomial(twoS, 1), syndrome, twoS);
			GenericGFPoly sigma = sigmaOmega[0];
			GenericGFPoly omega = sigmaOmega[1];
			int[] errorLocations = findErrorLocations(sigma);
			int[] errorMagnitudes = findErrorMagnitudes(omega, errorLocations, dataMatrix);
			for (int i = 0; i < errorLocations.Length; i++)
			{
				int position = received.Length - 1 - field.log(errorLocations[i]);
				if (position < 0)
				{
					throw new ReedSolomonException("Bad error location");
				}
				received[position] = GenericGF.addOrSubtract(received[position], errorMagnitudes[i]);
			}
		}

		//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET:
		//ORIGINAL LINE: private GenericGFPoly[] runEuclideanAlgorithm(GenericGFPoly a, GenericGFPoly b, int R) throws ReedSolomonException
		private GenericGFPoly[] runEuclideanAlgorithm(GenericGFPoly a, GenericGFPoly b, int R)
		{
			// Assume a's degree is >= b's
			if (a.Degree < b.Degree)
			{
				GenericGFPoly temp = a;
				a = b;
				b = temp;
			}

			GenericGFPoly rLast = a;
			GenericGFPoly r = b;
			GenericGFPoly tLast = field.Zero;
			GenericGFPoly t = field.One;

			// Run Euclidean algorithm until r's degree is less than R/2
			while (r.Degree >= R / 2)
			{
				GenericGFPoly rLastLast = rLast;
				GenericGFPoly tLastLast = tLast;
				rLast = r;
				tLast = t;

				// Divide rLastLast by rLast, with quotient in q and remainder in r
				if (rLast.Zero)
				{
					// Oops, Euclidean algorithm already terminated?
					throw new ReedSolomonException("r_{i-1} was zero");
				}
				r = rLastLast;
				GenericGFPoly q = field.Zero;
				int denominatorLeadingTerm = rLast.getCoefficient(rLast.Degree);
				int dltInverse = field.inverse(denominatorLeadingTerm);
				while (r.Degree >= rLast.Degree && !r.Zero)
				{
					int degreeDiff = r.Degree - rLast.Degree;
					int scale = field.multiply(r.getCoefficient(r.Degree), dltInverse);
					q = q.addOrSubtract(field.buildMonomial(degreeDiff, scale));
					r = r.addOrSubtract(rLast.multiplyByMonomial(degreeDiff, scale));
				}

				t = q.multiply(tLast).addOrSubtract(tLastLast);
			}

			int sigmaTildeAtZero = t.getCoefficient(0);
			if (sigmaTildeAtZero == 0)
			{
				throw new ReedSolomonException("sigmaTilde(0) was zero");
			}

			int inverse = field.inverse(sigmaTildeAtZero);
			GenericGFPoly sigma = t.multiply(inverse);
			GenericGFPoly omega = r.multiply(inverse);
			return new GenericGFPoly[] { sigma, omega };
		}

		//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET:
		//ORIGINAL LINE: private int[] findErrorLocations(GenericGFPoly errorLocator) throws ReedSolomonException
		private int[] findErrorLocations(GenericGFPoly errorLocator)
		{
			// This is a direct application of Chien's search
			int numErrors = errorLocator.Degree;
			if (numErrors == 1) // shortcut
			{
				return new int[] { errorLocator.getCoefficient(1) };
			}
			int[] result = new int[numErrors];
			int e = 0;
			for (int i = 1; i < field.Size && e < numErrors; i++)
			{
				if (errorLocator.evaluateAt(i) == 0)
				{
					result[e] = field.inverse(i);
					e++;
				}
			}
			if (e != numErrors)
			{
				throw new ReedSolomonException("Error locator degree does not match number of roots");
			}
			return result;
		}

		private int[] findErrorMagnitudes(GenericGFPoly errorEvaluator, int[] errorLocations, bool dataMatrix)
		{
			// This is directly applying Forney's Formula
			int s = errorLocations.Length;
			int[] result = new int[s];
			for (int i = 0; i < s; i++)
			{
				int xiInverse = field.inverse(errorLocations[i]);
				int denominator = 1;
				for (int j = 0; j < s; j++)
				{
					if (i != j)
					{
						//denominator = field.multiply(denominator,
						//    GenericGF.addOrSubtract(1, field.multiply(errorLocations[j], xiInverse)));
						// Above should work but fails on some Apple and Linux JDKs due to a Hotspot bug.
						// Below is a funny-looking workaround from Steven Parkes
						int term = field.multiply(errorLocations[j], xiInverse);
						int termPlus1 = (term & 0x1) == 0 ? term | 1 : term & ~1;
						denominator = field.multiply(denominator, termPlus1);
					}
				}
				result[i] = field.multiply(errorEvaluator.evaluateAt(xiInverse), field.inverse(denominator));
				// Thanks to sanfordsquires for this fix:
				if (dataMatrix)
				{
					result[i] = field.multiply(result[i], xiInverse);
				}
			}
			return result;
		}

	}

	/// <summary>
	/// <p>Implements Reed-Solomon enbcoding, as the name implies.</p>
	/// 
	/// @author Sean Owen
	/// @author William Rucklidge
	/// </summary>
	public sealed class ReedSolomonEncoder
	{

		private readonly GenericGF field;
		private readonly IList<GenericGFPoly> cachedGenerators;

		public ReedSolomonEncoder(GenericGF field)
		{
			if (!GenericGF.QR_CODE_FIELD_256.Equals(field))
			{
				throw new System.ArgumentException("Only QR Code is supported at this time");
			}
			this.field = field;
			this.cachedGenerators = new List<GenericGFPoly>();
			cachedGenerators.Add(new GenericGFPoly(field, new int[] { 1 }));
		}

		private GenericGFPoly buildGenerator(int degree)
		{
			if (degree >= cachedGenerators.Count)
			{
				GenericGFPoly lastGenerator = cachedGenerators[cachedGenerators.Count - 1];
				for (int d = cachedGenerators.Count; d <= degree; d++)
				{
					GenericGFPoly nextGenerator = lastGenerator.multiply(new GenericGFPoly(field, new int[] { 1, field.exp(d - 1) }));
					cachedGenerators.Add(nextGenerator);
					lastGenerator = nextGenerator;
				}
			}
			return cachedGenerators[degree];
		}

		public void encode(int[] toEncode, int ecBytes)
		{
			if (ecBytes == 0)
			{
				throw new System.ArgumentException("No error correction bytes");
			}
			int dataBytes = toEncode.Length - ecBytes;
			if (dataBytes <= 0)
			{
				throw new System.ArgumentException("No data bytes provided");
			}
			GenericGFPoly generator = buildGenerator(ecBytes);
			int[] infoCoefficients = new int[dataBytes];
			Array.Copy(toEncode, 0, infoCoefficients, 0, dataBytes);
			GenericGFPoly info = new GenericGFPoly(field, infoCoefficients);
			info = info.multiplyByMonomial(ecBytes, 1);
			GenericGFPoly remainder = info.divide(generator)[1];
			int[] coefficients = remainder.Coefficients;
			int numZeroCoefficients = ecBytes - coefficients.Length;
			for (int i = 0; i < numZeroCoefficients; i++)
			{
				toEncode[dataBytes + i] = 0;
			}
			Array.Copy(coefficients, 0, toEncode, dataBytes + numZeroCoefficients, coefficients.Length);
		}

	}

	/// <summary>
	/// <p>Thrown when an exception occurs during Reed-Solomon decoding, such as when
	/// there are too many errors to correct.</p>
	/// 
	/// @author Sean Owen
	/// </summary>
	public sealed class ReedSolomonException : Exception
	{

		public ReedSolomonException(string message)
			: base(message)
		{
		}

	}

	/// <summary>
	/// This implementation can detect and decode Data Matrix codes in an image.
	/// 
	/// @author bbrown@google.com (Brian Brown)
	/// </summary>
	public sealed class DataMatrixReader : Reader
	{

		private static readonly ResultPoint[] NO_POINTS = new ResultPoint[0];

		private readonly Decoder decoder = new Decoder();

		/// <summary>
		/// Locates and decodes a Data Matrix code in an image.
		/// </summary>
		/// <returns> a String representing the content encoded by the Data Matrix code </returns>
		/// <exception cref="NotFoundException"> if a Data Matrix code cannot be found </exception>
		/// <exception cref="FormatException"> if a Data Matrix code cannot be decoded </exception>
		/// <exception cref="ChecksumException"> if error correction fails </exception>
		//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET:
		//ORIGINAL LINE: public com.google.zxing.Result decode(com.google.zxing.BinaryBitmap image) throws com.google.zxing.NotFoundException, com.google.zxing.ChecksumException, com.google.zxing.FormatException
		public Result decode(BinaryBitmap image)
		{
			return decode(image, null);
		}

		//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET:
		//ORIGINAL LINE: public com.google.zxing.Result decode(com.google.zxing.BinaryBitmap image, java.util.Map<com.google.zxing.DecodeHintType,?> hints) throws com.google.zxing.NotFoundException, com.google.zxing.ChecksumException, com.google.zxing.FormatException
		public Result decode(BinaryBitmap image, IDictionary<DecodeHintType, object> hints)
		{
			DecoderResult decoderResult;
			ResultPoint[] points;
			if (hints != null && hints.ContainsKey(DecodeHintType.PURE_BARCODE))
			{
				BitMatrix bits = extractPureBits(image.BlackMatrix);
				decoderResult = decoder.decode(bits);
				points = NO_POINTS;
			}
			else
			{
				DetectorResult detectorResult = (new Detector(image.BlackMatrix)).detect();
				decoderResult = decoder.decode(detectorResult.Bits);
				points = detectorResult.Points;
			}
			Result result = new Result(decoderResult.Text, decoderResult.RawBytes, points, BarcodeFormat.DATA_MATRIX);
			IList<sbyte[]> byteSegments = decoderResult.ByteSegments;
			if (byteSegments != null)
			{
				result.putMetadata(ResultMetadataType.BYTE_SEGMENTS, byteSegments);
			}
			string ecLevel = decoderResult.ECLevel;
			if (ecLevel != null)
			{
				result.putMetadata(ResultMetadataType.ERROR_CORRECTION_LEVEL, ecLevel);
			}
			return result;
		}

		public void reset()
		{
			// do nothing
		}

		/// <summary>
		/// This method detects a code in a "pure" image -- that is, pure monochrome image
		/// which contains only an unrotated, unskewed, image of a code, with some white border
		/// around it. This is a specialized method that works exceptionally fast in this special
		/// case.
		/// </summary>
		/// <seealso cref= com.google.zxing.pdf417.PDF417Reader#extractPureBits(BitMatrix) </seealso>
		/// <seealso cref= com.google.zxing.qrcode.QRCodeReader#extractPureBits(BitMatrix) </seealso>
		//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET:
		//ORIGINAL LINE: private static com.google.zxing.common.BitMatrix extractPureBits(com.google.zxing.common.BitMatrix image) throws com.google.zxing.NotFoundException
		private static BitMatrix extractPureBits(BitMatrix image)
		{

			int[] leftTopBlack = image.TopLeftOnBit;
			int[] rightBottomBlack = image.BottomRightOnBit;
			if (leftTopBlack == null || rightBottomBlack == null)
			{
				throw NotFoundException.NotFoundInstance;
			}

			int moduleSize = getModuleSize(leftTopBlack, image);

			int top = leftTopBlack[1];
			int bottom = rightBottomBlack[1];
			int left = leftTopBlack[0];
			int right = rightBottomBlack[0];

			int matrixWidth = (right - left + 1) / moduleSize;
			int matrixHeight = (bottom - top + 1) / moduleSize;
			if (matrixWidth <= 0 || matrixHeight <= 0)
			{
				throw NotFoundException.NotFoundInstance;
			}

			// Push in the "border" by half the module width so that we start
			// sampling in the middle of the module. Just in case the image is a
			// little off, this will help recover.
			int nudge = moduleSize >> 1;
			top += nudge;
			left += nudge;

			// Now just read off the bits
			BitMatrix bits = new BitMatrix(matrixWidth, matrixHeight);
			for (int y = 0; y < matrixHeight; y++)
			{
				int iOffset = top + y * moduleSize;
				for (int x = 0; x < matrixWidth; x++)
				{
					if (image.get(left + x * moduleSize, iOffset))
					{
						bits.set(x, y);
					}
				}
			}
			return bits;
		}

		//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET:
		//ORIGINAL LINE: private static int moduleSize(int[] leftTopBlack, com.google.zxing.common.BitMatrix image) throws com.google.zxing.NotFoundException
		private static int getModuleSize(int[] leftTopBlack, BitMatrix image)
		{
			int width = image.Width;
			int x = leftTopBlack[0];
			int y = leftTopBlack[1];
			while (x < width && image.get(x, y))
			{
				x++;
			}
			if (x == width)
			{
				throw NotFoundException.NotFoundInstance;
			}

			int moduleSize = x - leftTopBlack[0];
			if (moduleSize == 0)
			{
				throw NotFoundException.NotFoundInstance;
			}
			return moduleSize;
		}

	}

	/// <summary>
	/// @author bbrown@google.com (Brian Brown)
	/// </summary>
	internal sealed class BitMatrixParser
	{

		private readonly BitMatrix mappingBitMatrix;
		private readonly BitMatrix readMappingMatrix;
		private readonly Version version;

		/// <param name="bitMatrix"> <seealso cref="BitMatrix"/> to parse </param>
		/// <exception cref="FormatException"> if dimension is < 8 or > 144 or not 0 mod 2 </exception>
		//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET:
		//ORIGINAL LINE: BitMatrixParser(com.google.zxing.common.BitMatrix bitMatrix) throws com.google.zxing.FormatException
		internal BitMatrixParser(BitMatrix bitMatrix)
		{
			int dimension = bitMatrix.Height;
			if (dimension < 8 || dimension > 144 || (dimension & 0x01) != 0)
			{
				throw FormatException.FormatInstance;
			}

			version = readVersion(bitMatrix);
			this.mappingBitMatrix = extractDataRegion(bitMatrix);
			this.readMappingMatrix = new BitMatrix(this.mappingBitMatrix.Width, this.mappingBitMatrix.Height);
		}

		internal Version Version
		{
			get
			{
				return version;
			}
		}

		/// <summary>
		/// <p>Creates the version object based on the dimension of the original bit matrix from 
		/// the datamatrix code.</p>
		/// 
		/// <p>See ISO 16022:2006 Table 7 - ECC 200 symbol attributes</p>
		/// </summary>
		/// <param name="bitMatrix"> Original <seealso cref="BitMatrix"/> including alignment patterns </param>
		/// <returns> <seealso cref="Version"/> encapsulating the Data Matrix Code's "version" </returns>
		/// <exception cref="FormatException"> if the dimensions of the mapping matrix are not valid
		/// Data Matrix dimensions. </exception>
		//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET:
		//ORIGINAL LINE: private static Version readVersion(com.google.zxing.common.BitMatrix bitMatrix) throws com.google.zxing.FormatException
		private static Version readVersion(BitMatrix bitMatrix)
		{
			int numRows = bitMatrix.Height;
			int numColumns = bitMatrix.Width;
			return Version.getVersionForDimensions(numRows, numColumns);
		}

		/// <summary>
		/// <p>Reads the bits in the <seealso cref="BitMatrix"/> representing the mapping matrix (No alignment patterns)
		/// in the correct order in order to reconstitute the codewords bytes contained within the
		/// Data Matrix Code.</p>
		/// </summary>
		/// <returns> bytes encoded within the Data Matrix Code </returns>
		/// <exception cref="FormatException"> if the exact number of bytes expected is not read </exception>
		//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET:
		//ORIGINAL LINE: byte[] readCodewords() throws com.google.zxing.FormatException
		internal sbyte[] readCodewords()
		{

			sbyte[] result = new sbyte[version.TotalCodewords];
			int resultOffset = 0;

			int row = 4;
			int column = 0;

			int numRows = mappingBitMatrix.Height;
			int numColumns = mappingBitMatrix.Width;

			bool corner1Read = false;
			bool corner2Read = false;
			bool corner3Read = false;
			bool corner4Read = false;

			// Read all of the codewords
			do
			{
				// Check the four corner cases
				if ((row == numRows) && (column == 0) && !corner1Read)
				{
					result[resultOffset++] = (sbyte)readCorner1(numRows, numColumns);
					row -= 2;
					column += 2;
					corner1Read = true;
				}
				else if ((row == numRows - 2) && (column == 0) && ((numColumns & 0x03) != 0) && !corner2Read)
				{
					result[resultOffset++] = (sbyte)readCorner2(numRows, numColumns);
					row -= 2;
					column += 2;
					corner2Read = true;
				}
				else if ((row == numRows + 4) && (column == 2) && ((numColumns & 0x07) == 0) && !corner3Read)
				{
					result[resultOffset++] = (sbyte)readCorner3(numRows, numColumns);
					row -= 2;
					column += 2;
					corner3Read = true;
				}
				else if ((row == numRows - 2) && (column == 0) && ((numColumns & 0x07) == 4) && !corner4Read)
				{
					result[resultOffset++] = (sbyte)readCorner4(numRows, numColumns);
					row -= 2;
					column += 2;
					corner4Read = true;
				}
				else
				{
					// Sweep upward diagonally to the right
					do
					{
						if ((row < numRows) && (column >= 0) && !readMappingMatrix.get(column, row))
						{
							result[resultOffset++] = (sbyte)readUtah(row, column, numRows, numColumns);
						}
						row -= 2;
						column += 2;
					} while ((row >= 0) && (column < numColumns));
					row += 1;
					column += 3;

					// Sweep downward diagonally to the left
					do
					{
						if ((row >= 0) && (column < numColumns) && !readMappingMatrix.get(column, row))
						{
							result[resultOffset++] = (sbyte)readUtah(row, column, numRows, numColumns);
						}
						row += 2;
						column -= 2;
					} while ((row < numRows) && (column >= 0));
					row += 3;
					column += 1;
				}
			} while ((row < numRows) || (column < numColumns));

			if (resultOffset != version.TotalCodewords)
			{
				throw FormatException.FormatInstance;
			}
			return result;
		}

		/// <summary>
		/// <p>Reads a bit of the mapping matrix accounting for boundary wrapping.</p>
		/// </summary>
		/// <param name="row"> Row to read in the mapping matrix </param>
		/// <param name="column"> Column to read in the mapping matrix </param>
		/// <param name="numRows"> Number of rows in the mapping matrix </param>
		/// <param name="numColumns"> Number of columns in the mapping matrix </param>
		/// <returns> value of the given bit in the mapping matrix </returns>
		internal bool readModule(int row, int column, int numRows, int numColumns)
		{
			// Adjust the row and column indices based on boundary wrapping
			if (row < 0)
			{
				row += numRows;
				column += 4 - ((numRows + 4) & 0x07);
			}
			if (column < 0)
			{
				column += numColumns;
				row += 4 - ((numColumns + 4) & 0x07);
			}
			readMappingMatrix.set(column, row);
			return mappingBitMatrix.get(column, row);
		}

		/// <summary>
		/// <p>Reads the 8 bits of the standard Utah-shaped pattern.</p>
		/// 
		/// <p>See ISO 16022:2006, 5.8.1 Figure 6</p>
		/// </summary>
		/// <param name="row"> Current row in the mapping matrix, anchored at the 8th bit (LSB) of the pattern </param>
		/// <param name="column"> Current column in the mapping matrix, anchored at the 8th bit (LSB) of the pattern </param>
		/// <param name="numRows"> Number of rows in the mapping matrix </param>
		/// <param name="numColumns"> Number of columns in the mapping matrix </param>
		/// <returns> byte from the utah shape </returns>
		internal int readUtah(int row, int column, int numRows, int numColumns)
		{
			int currentByte = 0;
			if (readModule(row - 2, column - 2, numRows, numColumns))
			{
				currentByte |= 1;
			}
			currentByte <<= 1;
			if (readModule(row - 2, column - 1, numRows, numColumns))
			{
				currentByte |= 1;
			}
			currentByte <<= 1;
			if (readModule(row - 1, column - 2, numRows, numColumns))
			{
				currentByte |= 1;
			}
			currentByte <<= 1;
			if (readModule(row - 1, column - 1, numRows, numColumns))
			{
				currentByte |= 1;
			}
			currentByte <<= 1;
			if (readModule(row - 1, column, numRows, numColumns))
			{
				currentByte |= 1;
			}
			currentByte <<= 1;
			if (readModule(row, column - 2, numRows, numColumns))
			{
				currentByte |= 1;
			}
			currentByte <<= 1;
			if (readModule(row, column - 1, numRows, numColumns))
			{
				currentByte |= 1;
			}
			currentByte <<= 1;
			if (readModule(row, column, numRows, numColumns))
			{
				currentByte |= 1;
			}
			return currentByte;
		}

		/// <summary>
		/// <p>Reads the 8 bits of the special corner condition 1.</p>
		/// 
		/// <p>See ISO 16022:2006, Figure F.3</p>
		/// </summary>
		/// <param name="numRows"> Number of rows in the mapping matrix </param>
		/// <param name="numColumns"> Number of columns in the mapping matrix </param>
		/// <returns> byte from the Corner condition 1 </returns>
		internal int readCorner1(int numRows, int numColumns)
		{
			int currentByte = 0;
			if (readModule(numRows - 1, 0, numRows, numColumns))
			{
				currentByte |= 1;
			}
			currentByte <<= 1;
			if (readModule(numRows - 1, 1, numRows, numColumns))
			{
				currentByte |= 1;
			}
			currentByte <<= 1;
			if (readModule(numRows - 1, 2, numRows, numColumns))
			{
				currentByte |= 1;
			}
			currentByte <<= 1;
			if (readModule(0, numColumns - 2, numRows, numColumns))
			{
				currentByte |= 1;
			}
			currentByte <<= 1;
			if (readModule(0, numColumns - 1, numRows, numColumns))
			{
				currentByte |= 1;
			}
			currentByte <<= 1;
			if (readModule(1, numColumns - 1, numRows, numColumns))
			{
				currentByte |= 1;
			}
			currentByte <<= 1;
			if (readModule(2, numColumns - 1, numRows, numColumns))
			{
				currentByte |= 1;
			}
			currentByte <<= 1;
			if (readModule(3, numColumns - 1, numRows, numColumns))
			{
				currentByte |= 1;
			}
			return currentByte;
		}

		/// <summary>
		/// <p>Reads the 8 bits of the special corner condition 2.</p>
		/// 
		/// <p>See ISO 16022:2006, Figure F.4</p>
		/// </summary>
		/// <param name="numRows"> Number of rows in the mapping matrix </param>
		/// <param name="numColumns"> Number of columns in the mapping matrix </param>
		/// <returns> byte from the Corner condition 2 </returns>
		internal int readCorner2(int numRows, int numColumns)
		{
			int currentByte = 0;
			if (readModule(numRows - 3, 0, numRows, numColumns))
			{
				currentByte |= 1;
			}
			currentByte <<= 1;
			if (readModule(numRows - 2, 0, numRows, numColumns))
			{
				currentByte |= 1;
			}
			currentByte <<= 1;
			if (readModule(numRows - 1, 0, numRows, numColumns))
			{
				currentByte |= 1;
			}
			currentByte <<= 1;
			if (readModule(0, numColumns - 4, numRows, numColumns))
			{
				currentByte |= 1;
			}
			currentByte <<= 1;
			if (readModule(0, numColumns - 3, numRows, numColumns))
			{
				currentByte |= 1;
			}
			currentByte <<= 1;
			if (readModule(0, numColumns - 2, numRows, numColumns))
			{
				currentByte |= 1;
			}
			currentByte <<= 1;
			if (readModule(0, numColumns - 1, numRows, numColumns))
			{
				currentByte |= 1;
			}
			currentByte <<= 1;
			if (readModule(1, numColumns - 1, numRows, numColumns))
			{
				currentByte |= 1;
			}
			return currentByte;
		}

		/// <summary>
		/// <p>Reads the 8 bits of the special corner condition 3.</p>
		/// 
		/// <p>See ISO 16022:2006, Figure F.5</p>
		/// </summary>
		/// <param name="numRows"> Number of rows in the mapping matrix </param>
		/// <param name="numColumns"> Number of columns in the mapping matrix </param>
		/// <returns> byte from the Corner condition 3 </returns>
		internal int readCorner3(int numRows, int numColumns)
		{
			int currentByte = 0;
			if (readModule(numRows - 1, 0, numRows, numColumns))
			{
				currentByte |= 1;
			}
			currentByte <<= 1;
			if (readModule(numRows - 1, numColumns - 1, numRows, numColumns))
			{
				currentByte |= 1;
			}
			currentByte <<= 1;
			if (readModule(0, numColumns - 3, numRows, numColumns))
			{
				currentByte |= 1;
			}
			currentByte <<= 1;
			if (readModule(0, numColumns - 2, numRows, numColumns))
			{
				currentByte |= 1;
			}
			currentByte <<= 1;
			if (readModule(0, numColumns - 1, numRows, numColumns))
			{
				currentByte |= 1;
			}
			currentByte <<= 1;
			if (readModule(1, numColumns - 3, numRows, numColumns))
			{
				currentByte |= 1;
			}
			currentByte <<= 1;
			if (readModule(1, numColumns - 2, numRows, numColumns))
			{
				currentByte |= 1;
			}
			currentByte <<= 1;
			if (readModule(1, numColumns - 1, numRows, numColumns))
			{
				currentByte |= 1;
			}
			return currentByte;
		}

		/// <summary>
		/// <p>Reads the 8 bits of the special corner condition 4.</p>
		/// 
		/// <p>See ISO 16022:2006, Figure F.6</p>
		/// </summary>
		/// <param name="numRows"> Number of rows in the mapping matrix </param>
		/// <param name="numColumns"> Number of columns in the mapping matrix </param>
		/// <returns> byte from the Corner condition 4 </returns>
		internal int readCorner4(int numRows, int numColumns)
		{
			int currentByte = 0;
			if (readModule(numRows - 3, 0, numRows, numColumns))
			{
				currentByte |= 1;
			}
			currentByte <<= 1;
			if (readModule(numRows - 2, 0, numRows, numColumns))
			{
				currentByte |= 1;
			}
			currentByte <<= 1;
			if (readModule(numRows - 1, 0, numRows, numColumns))
			{
				currentByte |= 1;
			}
			currentByte <<= 1;
			if (readModule(0, numColumns - 2, numRows, numColumns))
			{
				currentByte |= 1;
			}
			currentByte <<= 1;
			if (readModule(0, numColumns - 1, numRows, numColumns))
			{
				currentByte |= 1;
			}
			currentByte <<= 1;
			if (readModule(1, numColumns - 1, numRows, numColumns))
			{
				currentByte |= 1;
			}
			currentByte <<= 1;
			if (readModule(2, numColumns - 1, numRows, numColumns))
			{
				currentByte |= 1;
			}
			currentByte <<= 1;
			if (readModule(3, numColumns - 1, numRows, numColumns))
			{
				currentByte |= 1;
			}
			return currentByte;
		}

		/// <summary>
		/// <p>Extracts the data region from a <seealso cref="BitMatrix"/> that contains
		/// alignment patterns.</p>
		/// </summary>
		/// <param name="bitMatrix"> Original <seealso cref="BitMatrix"/> with alignment patterns </param>
		/// <returns> BitMatrix that has the alignment patterns removed </returns>
		internal BitMatrix extractDataRegion(BitMatrix bitMatrix)
		{
			int symbolSizeRows = version.SymbolSizeRows;
			int symbolSizeColumns = version.SymbolSizeColumns;

			if (bitMatrix.Height != symbolSizeRows)
			{
				throw new System.ArgumentException("Dimension of bitMarix must match the version size");
			}

			int dataRegionSizeRows = version.DataRegionSizeRows;
			int dataRegionSizeColumns = version.DataRegionSizeColumns;

			int numDataRegionsRow = symbolSizeRows / dataRegionSizeRows;
			int numDataRegionsColumn = symbolSizeColumns / dataRegionSizeColumns;

			int sizeDataRegionRow = numDataRegionsRow * dataRegionSizeRows;
			int sizeDataRegionColumn = numDataRegionsColumn * dataRegionSizeColumns;

			BitMatrix bitMatrixWithoutAlignment = new BitMatrix(sizeDataRegionColumn, sizeDataRegionRow);
			for (int dataRegionRow = 0; dataRegionRow < numDataRegionsRow; ++dataRegionRow)
			{
				int dataRegionRowOffset = dataRegionRow * dataRegionSizeRows;
				for (int dataRegionColumn = 0; dataRegionColumn < numDataRegionsColumn; ++dataRegionColumn)
				{
					int dataRegionColumnOffset = dataRegionColumn * dataRegionSizeColumns;
					for (int i = 0; i < dataRegionSizeRows; ++i)
					{
						int readRowOffset = dataRegionRow * (dataRegionSizeRows + 2) + 1 + i;
						int writeRowOffset = dataRegionRowOffset + i;
						for (int j = 0; j < dataRegionSizeColumns; ++j)
						{
							int readColumnOffset = dataRegionColumn * (dataRegionSizeColumns + 2) + 1 + j;
							if (bitMatrix.get(readColumnOffset, readRowOffset))
							{
								int writeColumnOffset = dataRegionColumnOffset + j;
								bitMatrixWithoutAlignment.set(writeColumnOffset, writeRowOffset);
							}
						}
					}
				}
			}
			return bitMatrixWithoutAlignment;
		}

	}

	/// <summary>
	/// <p>Encapsulates a block of data within a Data Matrix Code. Data Matrix Codes may split their data into
	/// multiple blocks, each of which is a unit of data and error-correction codewords. Each
	/// is represented by an instance of this class.</p>
	/// 
	/// @author bbrown@google.com (Brian Brown)
	/// </summary>
	internal sealed class DataBlock
	{

		private readonly int numDataCodewords;
		private readonly sbyte[] codewords;

		private DataBlock(int numDataCodewords, sbyte[] codewords)
		{
			this.numDataCodewords = numDataCodewords;
			this.codewords = codewords;
		}

		/// <summary>
		/// <p>When Data Matrix Codes use multiple data blocks, they actually interleave the bytes of each of them.
		/// That is, the first byte of data block 1 to n is written, then the second bytes, and so on. This
		/// method will separate the data into original blocks.</p>
		/// </summary>
		/// <param name="rawCodewords"> bytes as read directly from the Data Matrix Code </param>
		/// <param name="version"> version of the Data Matrix Code </param>
		/// <returns> DataBlocks containing original bytes, "de-interleaved" from representation in the
		///         Data Matrix Code </returns>
		internal static DataBlock[] getDataBlocks(sbyte[] rawCodewords, Version version)
		{
			// Figure out the number and size of data blocks used by this version
			Version.ECBlocks ecBlocks = version.ECBlocks2;

			// First count the total number of data blocks
			int totalBlocks = 0;
			Version.ECB[] ecBlockArray = ecBlocks.GetECB;
			foreach (Version.ECB ecBlock in ecBlockArray)
			{
				totalBlocks += ecBlock.Count;
			}

			// Now establish DataBlocks of the appropriate size and number of data codewords
			DataBlock[] result = new DataBlock[totalBlocks];
			int numResultBlocks = 0;
			foreach (Version.ECB ecBlock in ecBlockArray)
			{
				for (int i = 0; i < ecBlock.Count; i++)
				{
					int numDataCodewords = ecBlock.DataCodewords;
					int numBlockCodewords = ecBlocks.ECCodewords + numDataCodewords;
					result[numResultBlocks++] = new DataBlock(numDataCodewords, new sbyte[numBlockCodewords]);
				}
			}

			// All blocks have the same amount of data, except that the last n
			// (where n may be 0) have 1 less byte. Figure out where these start.
			// TODO(bbrown): There is only one case where there is a difference for Data Matrix for size 144
			int longerBlocksTotalCodewords = result[0].codewords.Length;
			//int shorterBlocksTotalCodewords = longerBlocksTotalCodewords - 1;

			int longerBlocksNumDataCodewords = longerBlocksTotalCodewords - ecBlocks.ECCodewords;
			int shorterBlocksNumDataCodewords = longerBlocksNumDataCodewords - 1;
			// The last elements of result may be 1 element shorter for 144 matrix
			// first fill out as many elements as all of them have minus 1
			int rawCodewordsOffset = 0;
			for (int i = 0; i < shorterBlocksNumDataCodewords; i++)
			{
				for (int j = 0; j < numResultBlocks; j++)
				{
					result[j].codewords[i] = rawCodewords[rawCodewordsOffset++];
				}
			}

			// Fill out the last data block in the longer ones
			bool specialVersion = version.VersionNumber == 24;
			int numLongerBlocks = specialVersion ? 8 : numResultBlocks;
			for (int j = 0; j < numLongerBlocks; j++)
			{
				result[j].codewords[longerBlocksNumDataCodewords - 1] = rawCodewords[rawCodewordsOffset++];
			}

			// Now add in error correction blocks
			int max = result[0].codewords.Length;
			for (int i = longerBlocksNumDataCodewords; i < max; i++)
			{
				for (int j = 0; j < numResultBlocks; j++)
				{
					int iOffset = specialVersion && j > 7 ? i - 1 : i;
					result[j].codewords[iOffset] = rawCodewords[rawCodewordsOffset++];
				}
			}

			if (rawCodewordsOffset != rawCodewords.Length)
			{
				throw new System.ArgumentException();
			}

			return result;
		}

		internal int NumDataCodewords
		{
			get
			{
				return numDataCodewords;
			}
		}

		internal sbyte[] Codewords
		{
			get
			{
				return codewords;
			}
		}

	}

	/// <summary>
	/// <p>Data Matrix Codes can encode text as bits in one of several modes, and can use multiple modes
	/// in one Data Matrix Code. This class decodes the bits back into text.</p>
	/// 
	/// <p>See ISO 16022:2006, 5.2.1 - 5.2.9.2</p>
	/// 
	/// @author bbrown@google.com (Brian Brown)
	/// @author Sean Owen
	/// </summary>
	internal sealed class DecodedBitStreamParser
	{

		private enum Mode
		{
			PAD_ENCODE, // Not really a mode
			ASCII_ENCODE,
			C40_ENCODE,
			TEXT_ENCODE,
			ANSIX12_ENCODE,
			EDIFACT_ENCODE,
			BASE256_ENCODE
		}

		/// <summary>
		/// See ISO 16022:2006, Annex C Table C.1
		/// The C40 Basic Character Set (*'s used for placeholders for the shift values)
		/// </summary>
		private static readonly char[] C40_BASIC_SET_CHARS = { '*', '*', '*', ' ', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z' };

		private static readonly char[] C40_SHIFT2_SET_CHARS = { '!', '"', '#', '$', '%', '&', '\'', '(', ')', '*', '+', ',', '-', '.', '/', ':', ';', '<', '=', '>', '?', '@', '[', '\\', ']', '^', '_' };

		/// <summary>
		/// See ISO 16022:2006, Annex C Table C.2
		/// The Text Basic Character Set (*'s used for placeholders for the shift values)
		/// </summary>
		private static readonly char[] TEXT_BASIC_SET_CHARS = { '*', '*', '*', ' ', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z' };

		private static readonly char[] TEXT_SHIFT3_SET_CHARS = { '\'', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '{', '|', '}', '~', (char)127 };

		private DecodedBitStreamParser()
		{
		}

		//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET:
		//ORIGINAL LINE: static com.google.zxing.common.DecoderResult decode(byte[] bytes) throws com.google.zxing.FormatException
		internal static DecoderResult decode(sbyte[] bytes)
		{
			BitSource bits = new BitSource(bytes);
			StringBuilder result = new StringBuilder(100);
			StringBuilder resultTrailer = new StringBuilder(0);
			IList<sbyte[]> byteSegments = new List<sbyte[]>(1);
			Mode mode = Mode.ASCII_ENCODE;
			do
			{
				if (mode == Mode.ASCII_ENCODE)
				{
					mode = decodeAsciiSegment(bits, result, resultTrailer);
				}
				else
				{
					switch (mode)
					{
						case com.google.zxing.datamatrix.decoder.DecodedBitStreamParser.Mode.C40_ENCODE:
							decodeC40Segment(bits, result);
							break;
						case com.google.zxing.datamatrix.decoder.DecodedBitStreamParser.Mode.TEXT_ENCODE:
							decodeTextSegment(bits, result);
							break;
						case com.google.zxing.datamatrix.decoder.DecodedBitStreamParser.Mode.ANSIX12_ENCODE:
							decodeAnsiX12Segment(bits, result);
							break;
						case com.google.zxing.datamatrix.decoder.DecodedBitStreamParser.Mode.EDIFACT_ENCODE:
							decodeEdifactSegment(bits, result);
							break;
						case com.google.zxing.datamatrix.decoder.DecodedBitStreamParser.Mode.BASE256_ENCODE:
							decodeBase256Segment(bits, result, byteSegments);
							break;
						default:
							throw FormatException.FormatInstance;
					}
					mode = Mode.ASCII_ENCODE;
				}
			} while (mode != Mode.PAD_ENCODE && bits.available() > 0);
			if (resultTrailer.Length > 0)
			{
				result.Append(resultTrailer.ToString());
			}
			return new DecoderResult(bytes, result.ToString(), byteSegments.Count == 0 ? null : byteSegments, null);
		}

		/// <summary>
		/// See ISO 16022:2006, 5.2.3 and Annex C, Table C.2
		/// </summary>
		//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET:
		//ORIGINAL LINE: private static Mode decodeAsciiSegment(com.google.zxing.common.BitSource bits, StringBuilder result, StringBuilder resultTrailer) throws com.google.zxing.FormatException
		private static Mode decodeAsciiSegment(BitSource bits, StringBuilder result, StringBuilder resultTrailer)
		{
			bool upperShift = false;
			do
			{
				int oneByte = bits.readBits(8);
				if (oneByte == 0)
				{
					throw FormatException.FormatInstance;
				} // ASCII data (ASCII value + 1)
				else if (oneByte <= 128)
				{
					if (upperShift)
					{
						oneByte += 128;
						//upperShift = false;
					}
					result.Append((char)(oneByte - 1));
					return Mode.ASCII_ENCODE;
				} // Pad
				else if (oneByte == 129)
				{
					return Mode.PAD_ENCODE;
				} // 2-digit data 00-99 (Numeric Value + 130)
				else if (oneByte <= 229)
				{
					int value = oneByte - 130;
					if (value < 10) // padd with '0' for single digit values
					{
						result.Append('0');
					}
					result.Append(value);
				} // Latch to C40 encodation
				else if (oneByte == 230)
				{
					return Mode.C40_ENCODE;
				} // Latch to Base 256 encodation
				else if (oneByte == 231)
				{
					return Mode.BASE256_ENCODE;
				}
				else if (oneByte == 232)
				{
					// FNC1
					result.Append((char)29); // translate as ASCII 29
				}
				else if (oneByte == 233 || oneByte == 234)
				{
					// Structured Append, Reader Programming
					// Ignore these symbols for now
					//throw ReaderException.getInstance();
				} // Upper Shift (shift to Extended ASCII)
				else if (oneByte == 235)
				{
					upperShift = true;
				} // 05 Macro
				else if (oneByte == 236)
				{
					result.Append("[)>\u001E05\u001D");
					resultTrailer.Insert(0, "\u001E\u0004");
				} // 06 Macro
				else if (oneByte == 237)
				{
					result.Append("[)>\u001E06\u001D");
					resultTrailer.Insert(0, "\u001E\u0004");
				} // Latch to ANSI X12 encodation
				else if (oneByte == 238)
				{
					return Mode.ANSIX12_ENCODE;
				} // Latch to Text encodation
				else if (oneByte == 239)
				{
					return Mode.TEXT_ENCODE;
				} // Latch to EDIFACT encodation
				else if (oneByte == 240)
				{
					return Mode.EDIFACT_ENCODE;
				} // ECI Character
				else if (oneByte == 241)
				{
					// TODO(bbrown): I think we need to support ECI
					//throw ReaderException.getInstance();
					// Ignore this symbol for now
				} // Not to be used in ASCII encodation
				else if (oneByte >= 242)
				{
					// ... but work around encoders that end with 254, latch back to ASCII
					if (oneByte != 254 || bits.available() != 0)
					{
						throw FormatException.FormatInstance;
					}
				}
			} while (bits.available() > 0);
			return Mode.ASCII_ENCODE;
		}

		/// <summary>
		/// See ISO 16022:2006, 5.2.5 and Annex C, Table C.1
		/// </summary>
		//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET:
		//ORIGINAL LINE: private static void decodeC40Segment(com.google.zxing.common.BitSource bits, StringBuilder result) throws com.google.zxing.FormatException
		private static void decodeC40Segment(BitSource bits, StringBuilder result)
		{
			// Three C40 values are encoded in a 16-bit value as
			// (1600 * C1) + (40 * C2) + C3 + 1
			// TODO(bbrown): The Upper Shift with C40 doesn't work in the 4 value scenario all the time
			bool upperShift = false;

			int[] cValues = new int[3];
			int shift = 0;

			do
			{
				// If there is only one byte left then it will be encoded as ASCII
				if (bits.available() == 8)
				{
					return;
				}
				int firstByte = bits.readBits(8);
				if (firstByte == 254) // Unlatch codeword
				{
					return;
				}

				parseTwoBytes(firstByte, bits.readBits(8), cValues);

				for (int i = 0; i < 3; i++)
				{
					int cValue = cValues[i];
					switch (shift)
					{
						case 0:
							if (cValue < 3)
							{
								shift = cValue + 1;
							}
							else if (cValue < C40_BASIC_SET_CHARS.Length)
							{
								char c40char = C40_BASIC_SET_CHARS[cValue];
								if (upperShift)
								{
									result.Append((char)(c40char + 128));
									upperShift = false;
								}
								else
								{
									result.Append(c40char);
								}
							}
							else
							{
								throw FormatException.FormatInstance;
							}
							break;
						case 1:
							if (upperShift)
							{
								result.Append((char)(cValue + 128));
								upperShift = false;
							}
							else
							{
								result.Append((char)cValue);
							}
							shift = 0;
							break;
						case 2:
							if (cValue < C40_SHIFT2_SET_CHARS.Length)
							{
								char c40char = C40_SHIFT2_SET_CHARS[cValue];
								if (upperShift)
								{
									result.Append((char)(c40char + 128));
									upperShift = false;
								}
								else
								{
									result.Append(c40char);
								}
							} // FNC1
							else if (cValue == 27)
							{
								result.Append((char)29); // translate as ASCII 29
							} // Upper Shift
							else if (cValue == 30)
							{
								upperShift = true;
							}
							else
							{
								throw FormatException.FormatInstance;
							}
							shift = 0;
							break;
						case 3:
							if (upperShift)
							{
								result.Append((char)(cValue + 224));
								upperShift = false;
							}
							else
							{
								result.Append((char)(cValue + 96));
							}
							shift = 0;
							break;
						default:
							throw FormatException.FormatInstance;
					}
				}
			} while (bits.available() > 0);
		}

		/// <summary>
		/// See ISO 16022:2006, 5.2.6 and Annex C, Table C.2
		/// </summary>
		//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET:
		//ORIGINAL LINE: private static void decodeTextSegment(com.google.zxing.common.BitSource bits, StringBuilder result) throws com.google.zxing.FormatException
		private static void decodeTextSegment(BitSource bits, StringBuilder result)
		{
			// Three Text values are encoded in a 16-bit value as
			// (1600 * C1) + (40 * C2) + C3 + 1
			// TODO(bbrown): The Upper Shift with Text doesn't work in the 4 value scenario all the time
			bool upperShift = false;

			int[] cValues = new int[3];
			int shift = 0;
			do
			{
				// If there is only one byte left then it will be encoded as ASCII
				if (bits.available() == 8)
				{
					return;
				}
				int firstByte = bits.readBits(8);
				if (firstByte == 254) // Unlatch codeword
				{
					return;
				}

				parseTwoBytes(firstByte, bits.readBits(8), cValues);

				for (int i = 0; i < 3; i++)
				{
					int cValue = cValues[i];
					switch (shift)
					{
						case 0:
							if (cValue < 3)
							{
								shift = cValue + 1;
							}
							else if (cValue < TEXT_BASIC_SET_CHARS.Length)
							{
								char textChar = TEXT_BASIC_SET_CHARS[cValue];
								if (upperShift)
								{
									result.Append((char)(textChar + 128));
									upperShift = false;
								}
								else
								{
									result.Append(textChar);
								}
							}
							else
							{
								throw FormatException.FormatInstance;
							}
							break;
						case 1:
							if (upperShift)
							{
								result.Append((char)(cValue + 128));
								upperShift = false;
							}
							else
							{
								result.Append((char)cValue);
							}
							shift = 0;
							break;
						case 2:
							// Shift 2 for Text is the same encoding as C40
							if (cValue < C40_SHIFT2_SET_CHARS.Length)
							{
								char c40char = C40_SHIFT2_SET_CHARS[cValue];
								if (upperShift)
								{
									result.Append((char)(c40char + 128));
									upperShift = false;
								}
								else
								{
									result.Append(c40char);
								}
							} // FNC1
							else if (cValue == 27)
							{
								result.Append((char)29); // translate as ASCII 29
							} // Upper Shift
							else if (cValue == 30)
							{
								upperShift = true;
							}
							else
							{
								throw FormatException.FormatInstance;
							}
							shift = 0;
							break;
						case 3:
							if (cValue < TEXT_SHIFT3_SET_CHARS.Length)
							{
								char textChar = TEXT_SHIFT3_SET_CHARS[cValue];
								if (upperShift)
								{
									result.Append((char)(textChar + 128));
									upperShift = false;
								}
								else
								{
									result.Append(textChar);
								}
								shift = 0;
							}
							else
							{
								throw FormatException.FormatInstance;
							}
							break;
						default:
							throw FormatException.FormatInstance;
					}
				}
			} while (bits.available() > 0);
		}

		/// <summary>
		/// See ISO 16022:2006, 5.2.7
		/// </summary>
		//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET:
		//ORIGINAL LINE: private static void decodeAnsiX12Segment(com.google.zxing.common.BitSource bits, StringBuilder result) throws com.google.zxing.FormatException
		private static void decodeAnsiX12Segment(BitSource bits, StringBuilder result)
		{
			// Three ANSI X12 values are encoded in a 16-bit value as
			// (1600 * C1) + (40 * C2) + C3 + 1

			int[] cValues = new int[3];
			do
			{
				// If there is only one byte left then it will be encoded as ASCII
				if (bits.available() == 8)
				{
					return;
				}
				int firstByte = bits.readBits(8);
				if (firstByte == 254) // Unlatch codeword
				{
					return;
				}

				parseTwoBytes(firstByte, bits.readBits(8), cValues);

				for (int i = 0; i < 3; i++)
				{
					int cValue = cValues[i];
					if (cValue == 0) // X12 segment terminator <CR>
					{
						result.Append('\r');
					} // X12 segment separator *
					else if (cValue == 1)
					{
						result.Append('*');
					} // X12 sub-element separator >
					else if (cValue == 2)
					{
						result.Append('>');
					} // space
					else if (cValue == 3)
					{
						result.Append(' ');
					} // 0 - 9
					else if (cValue < 14)
					{
						result.Append((char)(cValue + 44));
					} // A - Z
					else if (cValue < 40)
					{
						result.Append((char)(cValue + 51));
					}
					else
					{
						throw FormatException.FormatInstance;
					}
				}
			} while (bits.available() > 0);
		}

		private static void parseTwoBytes(int firstByte, int secondByte, int[] result)
		{
			int fullBitValue = (firstByte << 8) + secondByte - 1;
			int temp = fullBitValue / 1600;
			result[0] = temp;
			fullBitValue -= temp * 1600;
			temp = fullBitValue / 40;
			result[1] = temp;
			result[2] = fullBitValue - temp * 40;
		}

		/// <summary>
		/// See ISO 16022:2006, 5.2.8 and Annex C Table C.3
		/// </summary>
		private static void decodeEdifactSegment(BitSource bits, StringBuilder result)
		{
			do
			{
				// If there is only two or less bytes left then it will be encoded as ASCII
				if (bits.available() <= 16)
				{
					return;
				}

				for (int i = 0; i < 4; i++)
				{
					int edifactValue = bits.readBits(6);

					// Check for the unlatch character
					if (edifactValue == 0x1F) // 011111
					{
						// Read rest of byte, which should be 0, and stop
						int bitsLeft = 8 - bits.BitOffset;
						if (bitsLeft != 8)
						{
							bits.readBits(bitsLeft);
						}
						return;
					}

					if ((edifactValue & 0x20) == 0) // no 1 in the leading (6th) bit
					{
						edifactValue |= 0x40; // Add a leading 01 to the 6 bit binary value
					}
					result.Append((char)edifactValue);
				}
			} while (bits.available() > 0);
		}

		/// <summary>
		/// See ISO 16022:2006, 5.2.9 and Annex B, B.2
		/// </summary>
		//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET:
		//ORIGINAL LINE: private static void decodeBase256Segment(com.google.zxing.common.BitSource bits, StringBuilder result, java.util.Collection<byte[]> byteSegments) throws com.google.zxing.FormatException
		private static void decodeBase256Segment(BitSource bits, StringBuilder result, ICollection<sbyte[]> byteSegments)
		{
			// Figure out how long the Base 256 Segment is.
			int codewordPosition = 1 + bits.ByteOffset; // position is 1-indexed
			int d1 = unrandomize255State(bits.readBits(8), codewordPosition++);
			int count;
			if (d1 == 0) // Read the remainder of the symbol
			{
				count = bits.available() / 8;
			}
			else if (d1 < 250)
			{
				count = d1;
			}
			else
			{
				count = 250 * (d1 - 249) + unrandomize255State(bits.readBits(8), codewordPosition++);
			}

			// We're seeing NegativeArraySizeException errors from users.
			if (count < 0)
			{
				throw FormatException.FormatInstance;
			}

			sbyte[] bytes = new sbyte[count];
			for (int i = 0; i < count; i++)
			{
				// Have seen this particular error in the wild, such as at
				// http://www.bcgen.com/demo/IDAutomationStreamingDataMatrix.aspx?MODE=3&D=Fred&PFMT=3&PT=F&X=0.3&O=0&LM=0.2
				if (bits.available() < 8)
				{
					throw FormatException.FormatInstance;
				}
				bytes[i] = (sbyte)unrandomize255State(bits.readBits(8), codewordPosition++);
			}
			byteSegments.Add(bytes);
			try
			{
				//result.Append(new string(bytes, "ISO8859_1"));
				result.Append(GetEncodedStringFromBuffer(bytes, "ISO-8859-1"));
			}
			catch (System.IO.IOException uee)
			{
				throw new InvalidOperationException("Platform does not support required encoding: " + uee);
			}
		}
		private static string GetEncodedStringFromBuffer(sbyte[] buffer, string encoding)
		{
			byte[] bytes = buffer.ToBytes();
			Encoding en = Encoding.GetEncoding(encoding);
			return en.GetString(bytes);
		}

		/// <summary>
		/// See ISO 16022:2006, Annex B, B.2
		/// </summary>
		private static int unrandomize255State(int randomizedBase256Codeword, int base256CodewordPosition)
		{
			int pseudoRandomNumber = ((149 * base256CodewordPosition) % 255) + 1;
			int tempVariable = randomizedBase256Codeword - pseudoRandomNumber;
			return tempVariable >= 0 ? tempVariable : tempVariable + 256;
		}

	}

	/// <summary>
	/// <p>The main class which implements Data Matrix Code decoding -- as opposed to locating and extracting
	/// the Data Matrix Code from an image.</p>
	/// 
	/// @author bbrown@google.com (Brian Brown)
	/// </summary>
	public sealed class Decoder
	{

		private readonly ReedSolomonDecoder rsDecoder;

		public Decoder()
		{
			rsDecoder = new ReedSolomonDecoder(GenericGF.DATA_MATRIX_FIELD_256);
		}

		/// <summary>
		/// <p>Convenience method that can decode a Data Matrix Code represented as a 2D array of booleans.
		/// "true" is taken to mean a black module.</p>
		/// </summary>
		/// <param name="image"> booleans representing white/black Data Matrix Code modules </param>
		/// <returns> text and bytes encoded within the Data Matrix Code </returns>
		/// <exception cref="FormatException"> if the Data Matrix Code cannot be decoded </exception>
		/// <exception cref="ChecksumException"> if error correction fails </exception>
		//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET:
		//ORIGINAL LINE: public com.google.zxing.common.DecoderResult decode(boolean[][] image) throws com.google.zxing.FormatException, com.google.zxing.ChecksumException
		public DecoderResult decode(bool[][] image)
		{
			int dimension = image.Length;
			BitMatrix bits = new BitMatrix(dimension);
			for (int i = 0; i < dimension; i++)
			{
				for (int j = 0; j < dimension; j++)
				{
					if (image[i][j])
					{
						bits.set(j, i);
					}
				}
			}
			return decode(bits);
		}

		/// <summary>
		/// <p>Decodes a Data Matrix Code represented as a <seealso cref="BitMatrix"/>. A 1 or "true" is taken
		/// to mean a black module.</p>
		/// </summary>
		/// <param name="bits"> booleans representing white/black Data Matrix Code modules </param>
		/// <returns> text and bytes encoded within the Data Matrix Code </returns>
		/// <exception cref="FormatException"> if the Data Matrix Code cannot be decoded </exception>
		/// <exception cref="ChecksumException"> if error correction fails </exception>
		//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET:
		//ORIGINAL LINE: public com.google.zxing.common.DecoderResult decode(com.google.zxing.common.BitMatrix bits) throws com.google.zxing.FormatException, com.google.zxing.ChecksumException
		public DecoderResult decode(BitMatrix bits)
		{

			// Construct a parser and read version, error-correction level
			BitMatrixParser parser = new BitMatrixParser(bits);
			Version version = parser.Version;

			// Read codewords
			sbyte[] codewords = parser.readCodewords();
			// Separate into data blocks
			DataBlock[] dataBlocks = DataBlock.getDataBlocks(codewords, version);

			int dataBlocksCount = dataBlocks.Length;

			// Count total number of data bytes
			int totalBytes = 0;
			foreach (DataBlock db in dataBlocks)
			{
				totalBytes += db.NumDataCodewords;
			}
			sbyte[] resultBytes = new sbyte[totalBytes];

			// Error-correct and copy data blocks together into a stream of bytes
			for (int j = 0; j < dataBlocksCount; j++)
			{
				DataBlock dataBlock = dataBlocks[j];
				sbyte[] codewordBytes = dataBlock.Codewords;
				int numDataCodewords = dataBlock.NumDataCodewords;
				correctErrors(codewordBytes, numDataCodewords);
				for (int i = 0; i < numDataCodewords; i++)
				{
					// De-interlace data blocks.
					resultBytes[i * dataBlocksCount + j] = codewordBytes[i];
				}
			}

			// Decode the contents of that stream of bytes
			return DecodedBitStreamParser.decode(resultBytes);
		}

		/// <summary>
		/// <p>Given data and error-correction codewords received, possibly corrupted by errors, attempts to
		/// correct the errors in-place using Reed-Solomon error correction.</p>
		/// </summary>
		/// <param name="codewordBytes"> data and error correction codewords </param>
		/// <param name="numDataCodewords"> number of codewords that are data bytes </param>
		/// <exception cref="ChecksumException"> if error correction fails </exception>
		//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET:
		//ORIGINAL LINE: private void correctErrors(byte[] codewordBytes, int numDataCodewords) throws com.google.zxing.ChecksumException
		private void correctErrors(sbyte[] codewordBytes, int numDataCodewords)
		{
			int numCodewords = codewordBytes.Length;
			// First read into an array of ints
			int[] codewordsInts = new int[numCodewords];
			for (int i = 0; i < numCodewords; i++)
			{
				codewordsInts[i] = codewordBytes[i] & 0xFF;
			}
			int numECCodewords = codewordBytes.Length - numDataCodewords;
			try
			{
				rsDecoder.decode(codewordsInts, numECCodewords);
			}
			catch (ReedSolomonException rse)
			{
				throw ChecksumException.ChecksumInstance;
			}
			// Copy back into array of bytes -- only need to worry about the bytes that were data
			// We don't care about errors in the error-correction codewords
			for (int i = 0; i < numDataCodewords; i++)
			{
				codewordBytes[i] = (sbyte)codewordsInts[i];
			}
		}

	}

	/// <summary>
	/// The Version object encapsulates attributes about a particular
	/// size Data Matrix Code.
	/// 
	/// @author bbrown@google.com (Brian Brown)
	/// </summary>
	public sealed class Version
	{

		private static readonly Version[] VERSIONS = buildVersions();

		private readonly int versionNumber;
		private readonly int symbolSizeRows;
		private readonly int symbolSizeColumns;
		private readonly int dataRegionSizeRows;
		private readonly int dataRegionSizeColumns;
		private readonly ECBlocks ecBlocks;
		private readonly int totalCodewords;

		private Version(int versionNumber, int symbolSizeRows, int symbolSizeColumns, int dataRegionSizeRows, int dataRegionSizeColumns, ECBlocks ecBlocks)
		{
			this.versionNumber = versionNumber;
			this.symbolSizeRows = symbolSizeRows;
			this.symbolSizeColumns = symbolSizeColumns;
			this.dataRegionSizeRows = dataRegionSizeRows;
			this.dataRegionSizeColumns = dataRegionSizeColumns;
			this.ecBlocks = ecBlocks;

			// Calculate the total number of codewords
			int total = 0;
			int ecCodewords = ecBlocks.ECCodewords;
			ECB[] ecbArray = ecBlocks.GetECB;
			foreach (ECB ecBlock in ecbArray)
			{
				total += ecBlock.Count * (ecBlock.DataCodewords + ecCodewords);
			}
			this.totalCodewords = total;
		}

		public int VersionNumber
		{
			get
			{
				return versionNumber;
			}
		}

		public int SymbolSizeRows
		{
			get
			{
				return symbolSizeRows;
			}
		}

		public int SymbolSizeColumns
		{
			get
			{
				return symbolSizeColumns;
			}
		}

		public int DataRegionSizeRows
		{
			get
			{
				return dataRegionSizeRows;
			}
		}

		public int DataRegionSizeColumns
		{
			get
			{
				return dataRegionSizeColumns;
			}
		}

		public int TotalCodewords
		{
			get
			{
				return totalCodewords;
			}
		}

		internal ECBlocks ECBlocks2
		{
			get
			{
				return ecBlocks;
			}
		}

		/// <summary>
		/// <p>Deduces version information from Data Matrix dimensions.</p>
		/// </summary>
		/// <param name="numRows"> Number of rows in modules </param>
		/// <param name="numColumns"> Number of columns in modules </param>
		/// <returns> Version for a Data Matrix Code of those dimensions </returns>
		/// <exception cref="FormatException"> if dimensions do correspond to a valid Data Matrix size </exception>
		//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET:
		//ORIGINAL LINE: public static Version getVersionForDimensions(int numRows, int numColumns) throws com.google.zxing.FormatException
		public static Version getVersionForDimensions(int numRows, int numColumns)
		{
			if ((numRows & 0x01) != 0 || (numColumns & 0x01) != 0)
			{
				throw FormatException.FormatInstance;
			}

			foreach (Version version in VERSIONS)
			{
				if (version.symbolSizeRows == numRows && version.symbolSizeColumns == numColumns)
				{
					return version;
				}
			}

			throw FormatException.FormatInstance;
		}

		/// <summary>
		/// <p>Encapsulates a set of error-correction blocks in one symbol version. Most versions will
		/// use blocks of differing sizes within one version, so, this encapsulates the parameters for
		/// each set of blocks. It also holds the number of error-correction codewords per block since it
		/// will be the same across all blocks within one version.</p>
		/// </summary>
		internal sealed class ECBlocks
		{
			private readonly int ecCodewords;
			private readonly ECB[] ecBlocks;

			internal ECBlocks(int ecCodewords, ECB ecBlocks)
			{
				this.ecCodewords = ecCodewords;
				this.ecBlocks = new ECB[] { ecBlocks };
			}

			internal ECBlocks(int ecCodewords, ECB ecBlocks1, ECB ecBlocks2)
			{
				this.ecCodewords = ecCodewords;
				this.ecBlocks = new ECB[] { ecBlocks1, ecBlocks2 };
			}

			internal int ECCodewords
			{
				get
				{
					return ecCodewords;
				}
			}

			internal ECB[] GetECB
			{
				get
				{
					return ecBlocks;
				}
			}
		}

		/// <summary>
		/// <p>Encapsualtes the parameters for one error-correction block in one symbol version.
		/// This includes the number of data codewords, and the number of times a block with these
		/// parameters is used consecutively in the Data Matrix code version's format.</p>
		/// </summary>
		internal sealed class ECB
		{
			private readonly int count;
			private readonly int dataCodewords;

			internal ECB(int count, int dataCodewords)
			{
				this.count = count;
				this.dataCodewords = dataCodewords;
			}

			internal int Count
			{
				get
				{
					return count;
				}
			}

			internal int DataCodewords
			{
				get
				{
					return dataCodewords;
				}
			}
		}

		public override string ToString()
		{
			return Convert.ToString(versionNumber);
		}

		/// <summary>
		/// See ISO 16022:2006 5.5.1 Table 7
		/// </summary>
		private static Version[] buildVersions()
		{
			return new Version[] { new Version(1, 10, 10, 8, 8, new ECBlocks(5, new ECB(1, 3))), new Version(2, 12, 12, 10, 10, new ECBlocks(7, new ECB(1, 5))), new Version(3, 14, 14, 12, 12, new ECBlocks(10, new ECB(1, 8))), new Version(4, 16, 16, 14, 14, new ECBlocks(12, new ECB(1, 12))), new Version(5, 18, 18, 16, 16, new ECBlocks(14, new ECB(1, 18))), new Version(6, 20, 20, 18, 18, new ECBlocks(18, new ECB(1, 22))), new Version(7, 22, 22, 20, 20, new ECBlocks(20, new ECB(1, 30))), new Version(8, 24, 24, 22, 22, new ECBlocks(24, new ECB(1, 36))), new Version(9, 26, 26, 24, 24, new ECBlocks(28, new ECB(1, 44))), new Version(10, 32, 32, 14, 14, new ECBlocks(36, new ECB(1, 62))), new Version(11, 36, 36, 16, 16, new ECBlocks(42, new ECB(1, 86))), new Version(12, 40, 40, 18, 18, new ECBlocks(48, new ECB(1, 114))), new Version(13, 44, 44, 20, 20, new ECBlocks(56, new ECB(1, 144))), new Version(14, 48, 48, 22, 22, new ECBlocks(68, new ECB(1, 174))), new Version(15, 52, 52, 24, 24, new ECBlocks(42, new ECB(2, 102))), new Version(16, 64, 64, 14, 14, new ECBlocks(56, new ECB(2, 140))), new Version(17, 72, 72, 16, 16, new ECBlocks(36, new ECB(4, 92))), new Version(18, 80, 80, 18, 18, new ECBlocks(48, new ECB(4, 114))), new Version(19, 88, 88, 20, 20, new ECBlocks(56, new ECB(4, 144))), new Version(20, 96, 96, 22, 22, new ECBlocks(68, new ECB(4, 174))), new Version(21, 104, 104, 24, 24, new ECBlocks(56, new ECB(6, 136))), new Version(22, 120, 120, 18, 18, new ECBlocks(68, new ECB(6, 175))), new Version(23, 132, 132, 20, 20, new ECBlocks(62, new ECB(8, 163))), new Version(24, 144, 144, 22, 22, new ECBlocks(62, new ECB(8, 156), new ECB(2, 155))), new Version(25, 8, 18, 6, 16, new ECBlocks(7, new ECB(1, 5))), new Version(26, 8, 32, 6, 14, new ECBlocks(11, new ECB(1, 10))), new Version(27, 12, 26, 10, 24, new ECBlocks(14, new ECB(1, 16))), new Version(28, 12, 36, 10, 16, new ECBlocks(18, new ECB(1, 22))), new Version(29, 16, 36, 14, 16, new ECBlocks(24, new ECB(1, 32))), new Version(30, 16, 48, 14, 22, new ECBlocks(28, new ECB(1, 49))) };
		}

	}

	/// <summary>
	/// <p>Encapsulates logic that can detect a Data Matrix Code in an image, even if the Data Matrix Code
	/// is rotated or skewed, or partially obscured.</p>
	/// 
	/// @author Sean Owen
	/// </summary>
	public sealed class Detector
	{

		private readonly BitMatrix image;
		private readonly WhiteRectangleDetector rectangleDetector;

		//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET:
		//ORIGINAL LINE: public Detector(com.google.zxing.common.BitMatrix image) throws com.google.zxing.NotFoundException
		public Detector(BitMatrix image)
		{
			this.image = image;
			rectangleDetector = new WhiteRectangleDetector(image);
		}

		/// <summary>
		/// <p>Detects a Data Matrix Code in an image.</p>
		/// </summary>
		/// <returns> <seealso cref="DetectorResult"/> encapsulating results of detecting a Data Matrix Code </returns>
		/// <exception cref="NotFoundException"> if no Data Matrix Code can be found </exception>
		//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET:
		//ORIGINAL LINE: public com.google.zxing.common.DetectorResult detect() throws com.google.zxing.NotFoundException
		public DetectorResult detect()
		{

			ResultPoint[] cornerPoints = rectangleDetector.detect();
			ResultPoint pointA = cornerPoints[0];
			ResultPoint pointB = cornerPoints[1];
			ResultPoint pointC = cornerPoints[2];
			ResultPoint pointD = cornerPoints[3];

			// Point A and D are across the diagonal from one another,
			// as are B and C. Figure out which are the solid black lines
			// by counting transitions
			List<ResultPointsAndTransitions> transitions = new List<ResultPointsAndTransitions>(4);
			transitions.Add(transitionsBetween(pointA, pointB));
			transitions.Add(transitionsBetween(pointA, pointC));
			transitions.Add(transitionsBetween(pointB, pointD));
			transitions.Add(transitionsBetween(pointC, pointD));
			transitions.Sort(new ResultPointsAndTransitionsComparator());

			// Sort by number of transitions. First two will be the two solid sides; last two
			// will be the two alternating black/white sides
			ResultPointsAndTransitions lSideOne = transitions[0];
			ResultPointsAndTransitions lSideTwo = transitions[1];

			// Figure out which point is their intersection by tallying up the number of times we see the
			// endpoints in the four endpoints. One will show up twice.
			IDictionary<ResultPoint, int?> pointCount = new Dictionary<ResultPoint, int?>();
			increment(pointCount, lSideOne.From);
			increment(pointCount, lSideOne.To);
			increment(pointCount, lSideTwo.From);
			increment(pointCount, lSideTwo.To);

			ResultPoint maybeTopLeft = null;
			ResultPoint bottomLeft = null;
			ResultPoint maybeBottomRight = null;
			foreach (KeyValuePair<ResultPoint, int?> entry in pointCount)
			{
				ResultPoint point = entry.Key;
				int? value = entry.Value;
				if (value == 2)
				{
					bottomLeft = point; // this is definitely the bottom left, then -- end of two L sides
				}
				else
				{
					// Otherwise it's either top left or bottom right -- just assign the two arbitrarily now
					if (maybeTopLeft == null)
					{
						maybeTopLeft = point;
					}
					else
					{
						maybeBottomRight = point;
					}
				}
			}

			if (maybeTopLeft == null || bottomLeft == null || maybeBottomRight == null)
			{
				throw NotFoundException.NotFoundInstance;
			}

			// Bottom left is correct but top left and bottom right might be switched
			ResultPoint[] corners = { maybeTopLeft, bottomLeft, maybeBottomRight };
			// Use the dot product trick to sort them out
			ResultPoint.orderBestPatterns(corners);

			// Now we know which is which:
			ResultPoint bottomRight = corners[0];
			bottomLeft = corners[1];
			ResultPoint topLeft = corners[2];

			// Which point didn't we find in relation to the "L" sides? that's the top right corner
			ResultPoint topRight;
			if (!pointCount.ContainsKey(pointA))
			{
				topRight = pointA;
			}
			else if (!pointCount.ContainsKey(pointB))
			{
				topRight = pointB;
			}
			else if (!pointCount.ContainsKey(pointC))
			{
				topRight = pointC;
			}
			else
			{
				topRight = pointD;
			}

			// Next determine the dimension by tracing along the top or right side and counting black/white
			// transitions. Since we start inside a black module, we should see a number of transitions
			// equal to 1 less than the code dimension. Well, actually 2 less, because we are going to
			// end on a black module:

			// The top right point is actually the corner of a module, which is one of the two black modules
			// adjacent to the white module at the top right. Tracing to that corner from either the top left
			// or bottom right should work here.

			int dimensionTop = transitionsBetween(topLeft, topRight).Transitions;
			int dimensionRight = transitionsBetween(bottomRight, topRight).Transitions;

			if ((dimensionTop & 0x01) == 1)
			{
				// it can't be odd, so, round... up?
				dimensionTop++;
			}
			dimensionTop += 2;

			if ((dimensionRight & 0x01) == 1)
			{
				// it can't be odd, so, round... up?
				dimensionRight++;
			}
			dimensionRight += 2;

			BitMatrix bits;
			ResultPoint correctedTopRight;

			// Rectanguar symbols are 6x16, 6x28, 10x24, 10x32, 14x32, or 14x44. If one dimension is more
			// than twice the other, it's certainly rectangular, but to cut a bit more slack we accept it as
			// rectangular if the bigger side is at least 7/4 times the other:
			if (4 * dimensionTop >= 7 * dimensionRight || 4 * dimensionRight >= 7 * dimensionTop)
			{
				// The matrix is rectangular

				correctedTopRight = correctTopRightRectangular(bottomLeft, bottomRight, topLeft, topRight, dimensionTop, dimensionRight);
				if (correctedTopRight == null)
				{
					correctedTopRight = topRight;
				}

				dimensionTop = transitionsBetween(topLeft, correctedTopRight).Transitions;
				dimensionRight = transitionsBetween(bottomRight, correctedTopRight).Transitions;

				if ((dimensionTop & 0x01) == 1)
				{
					// it can't be odd, so, round... up?
					dimensionTop++;
				}

				if ((dimensionRight & 0x01) == 1)
				{
					// it can't be odd, so, round... up?
					dimensionRight++;
				}

				bits = sampleGrid(image, topLeft, bottomLeft, bottomRight, correctedTopRight, dimensionTop, dimensionRight);

			}
			else
			{
				// The matrix is square

				int dimension = Math.Min(dimensionRight, dimensionTop);
				// correct top right point to match the white module
				correctedTopRight = correctTopRight(bottomLeft, bottomRight, topLeft, topRight, dimension);
				if (correctedTopRight == null)
				{
					correctedTopRight = topRight;
				}

				// Redetermine the dimension using the corrected top right point
				int dimensionCorrected = Math.Max(transitionsBetween(topLeft, correctedTopRight).Transitions, transitionsBetween(bottomRight, correctedTopRight).Transitions);
				dimensionCorrected++;
				if ((dimensionCorrected & 0x01) == 1)
				{
					dimensionCorrected++;
				}

				bits = sampleGrid(image, topLeft, bottomLeft, bottomRight, correctedTopRight, dimensionCorrected, dimensionCorrected);
			}

			return new DetectorResult(bits, new ResultPoint[] { topLeft, bottomLeft, bottomRight, correctedTopRight });
		}

		/// <summary>
		/// Calculates the position of the white top right module using the output of the rectangle detector
		/// for a rectangular matrix
		/// </summary>
		private ResultPoint correctTopRightRectangular(ResultPoint bottomLeft, ResultPoint bottomRight, ResultPoint topLeft, ResultPoint topRight, int dimensionTop, int dimensionRight)
		{

			float corr = distance(bottomLeft, bottomRight) / (float)dimensionTop;
			int norm = distance(topLeft, topRight);
			float cos = (topRight.X - topLeft.X) / norm;
			float sin = (topRight.Y - topLeft.Y) / norm;

			ResultPoint c1 = new ResultPoint(topRight.X + corr * cos, topRight.Y + corr * sin);

			corr = distance(bottomLeft, topLeft) / (float)dimensionRight;
			norm = distance(bottomRight, topRight);
			cos = (topRight.X - bottomRight.X) / norm;
			sin = (topRight.Y - bottomRight.Y) / norm;

			ResultPoint c2 = new ResultPoint(topRight.X + corr * cos, topRight.Y + corr * sin);

			if (!isValid(c1))
			{
				if (isValid(c2))
				{
					return c2;
				}
				return null;
			}
			if (!isValid(c2))
			{
				return c1;
			}

			int l1 = Math.Abs(dimensionTop - transitionsBetween(topLeft, c1).Transitions) + Math.Abs(dimensionRight - transitionsBetween(bottomRight, c1).Transitions);
			int l2 = Math.Abs(dimensionTop - transitionsBetween(topLeft, c2).Transitions) + Math.Abs(dimensionRight - transitionsBetween(bottomRight, c2).Transitions);

			if (l1 <= l2)
			{
				return c1;
			}

			return c2;
		}

		/// <summary>
		/// Calculates the position of the white top right module using the output of the rectangle detector
		/// for a square matrix
		/// </summary>
		private ResultPoint correctTopRight(ResultPoint bottomLeft, ResultPoint bottomRight, ResultPoint topLeft, ResultPoint topRight, int dimension)
		{

			float corr = distance(bottomLeft, bottomRight) / (float)dimension;
			int norm = distance(topLeft, topRight);
			float cos = (topRight.X - topLeft.X) / norm;
			float sin = (topRight.Y - topLeft.Y) / norm;

			ResultPoint c1 = new ResultPoint(topRight.X + corr * cos, topRight.Y + corr * sin);

			corr = distance(bottomLeft, topLeft) / (float)dimension;
			norm = distance(bottomRight, topRight);
			cos = (topRight.X - bottomRight.X) / norm;
			sin = (topRight.Y - bottomRight.Y) / norm;

			ResultPoint c2 = new ResultPoint(topRight.X + corr * cos, topRight.Y + corr * sin);

			if (!isValid(c1))
			{
				if (isValid(c2))
				{
					return c2;
				}
				return null;
			}
			if (!isValid(c2))
			{
				return c1;
			}

			int l1 = Math.Abs(transitionsBetween(topLeft, c1).Transitions - transitionsBetween(bottomRight, c1).Transitions);
			int l2 = Math.Abs(transitionsBetween(topLeft, c2).Transitions - transitionsBetween(bottomRight, c2).Transitions);

			return l1 <= l2 ? c1 : c2;
		}

		private bool isValid(ResultPoint p)
		{
			return p.X >= 0 && p.X < image.Width && p.Y > 0 && p.Y < image.Height;
		}

		private static int distance(ResultPoint a, ResultPoint b)
		{
			return MathUtils.round(ResultPoint.distance(a, b));
		}

		/// <summary>
		/// Increments the Integer associated with a key by one.
		/// </summary>
		private static void increment(IDictionary<ResultPoint, int?> table, ResultPoint key)
		{
			int? value = null;
			if (table.ContainsKey(key))
			{
				value = table[key];
			}

			table[key] = value == null ? 1 : value + 1;
		}

		//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET:
		//ORIGINAL LINE: private static com.google.zxing.common.BitMatrix sampleGrid(com.google.zxing.common.BitMatrix image, com.google.zxing.ResultPoint topLeft, com.google.zxing.ResultPoint bottomLeft, com.google.zxing.ResultPoint bottomRight, com.google.zxing.ResultPoint topRight, int dimensionX, int dimensionY) throws com.google.zxing.NotFoundException
		private static BitMatrix sampleGrid(BitMatrix image, ResultPoint topLeft, ResultPoint bottomLeft, ResultPoint bottomRight, ResultPoint topRight, int dimensionX, int dimensionY)
		{

			GridSampler sampler = GridSampler.Instance;

			return sampler.sampleGrid(image, dimensionX, dimensionY, 0.5f, 0.5f, dimensionX - 0.5f, 0.5f, dimensionX - 0.5f, dimensionY - 0.5f, 0.5f, dimensionY - 0.5f, topLeft.X, topLeft.Y, topRight.X, topRight.Y, bottomRight.X, bottomRight.Y, bottomLeft.X, bottomLeft.Y);
		}

		/// <summary>
		/// Counts the number of black/white transitions between two points, using something like Bresenham's algorithm.
		/// </summary>
		private ResultPointsAndTransitions transitionsBetween(ResultPoint from, ResultPoint to)
		{
			// See QR Code Detector, sizeOfBlackWhiteBlackRun()
			int fromX = (int)from.X;
			int fromY = (int)from.Y;
			int toX = (int)to.X;
			int toY = (int)to.Y;
			bool steep = Math.Abs(toY - fromY) > Math.Abs(toX - fromX);
			if (steep)
			{
				int temp = fromX;
				fromX = fromY;
				fromY = temp;
				temp = toX;
				toX = toY;
				toY = temp;
			}

			int dx = Math.Abs(toX - fromX);
			int dy = Math.Abs(toY - fromY);
			int error = -dx >> 1;
			int ystep = fromY < toY ? 1 : -1;
			int xstep = fromX < toX ? 1 : -1;
			int transitions = 0;
			bool inBlack = image.get(steep ? fromY : fromX, steep ? fromX : fromY);
			for (int x = fromX, y = fromY; x != toX; x += xstep)
			{
				bool isBlack = image.get(steep ? y : x, steep ? x : y);
				if (isBlack != inBlack)
				{
					transitions++;
					inBlack = isBlack;
				}
				error += dy;
				if (error > 0)
				{
					if (y == toY)
					{
						break;
					}
					y += ystep;
					error -= dx;
				}
			}
			return new ResultPointsAndTransitions(from, to, transitions);
		}

		/// <summary>
		/// Simply encapsulates two points and a number of transitions between them.
		/// </summary>
		private sealed class ResultPointsAndTransitions
		{

			private readonly ResultPoint from;
			private readonly ResultPoint to;
			private readonly int transitions;

			internal ResultPointsAndTransitions(ResultPoint from, ResultPoint to, int transitions)
			{
				this.from = from;
				this.to = to;
				this.transitions = transitions;
			}

			internal ResultPoint From
			{
				get
				{
					return from;
				}
			}

			internal ResultPoint To
			{
				get
				{
					return to;
				}
			}

			public int Transitions
			{
				get
				{
					return transitions;
				}
			}

			public override string ToString()
			{
				return from + "/" + to + '/' + transitions;
			}
		}

		/// <summary>
		/// Orders ResultPointsAndTransitions by number of transitions, ascending.
		/// </summary>
		[Serializable]
		private sealed class ResultPointsAndTransitionsComparator : IComparer<ResultPointsAndTransitions>
		{
			public int Compare(ResultPointsAndTransitions o1, ResultPointsAndTransitions o2)
			{
				return o1.Transitions - o2.Transitions;
			}
		}

	}

	/// <summary>
	/// This class attempts to decode a barcode from an image, not by scanning the whole image,
	/// but by scanning subsets of the image. This is important when there may be multiple barcodes in
	/// an image, and detecting a barcode may find parts of multiple barcode and fail to decode
	/// (e.g. QR Codes). Instead this scans the four quadrants of the image -- and also the center
	/// 'quadrant' to cover the case where a barcode is found in the center.
	/// </summary>
	/// <seealso cref= GenericMultipleBarcodeReader </seealso>
	public sealed class ByQuadrantReader : Reader
	{

		private readonly Reader @delegate;

		public ByQuadrantReader(Reader @delegate)
		{
			this.@delegate = @delegate;
		}

		//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET:
		//ORIGINAL LINE: public com.google.zxing.Result decode(com.google.zxing.BinaryBitmap image) throws com.google.zxing.NotFoundException, com.google.zxing.ChecksumException, com.google.zxing.FormatException
		public Result decode(BinaryBitmap image)
		{
			return decode(image, null);
		}

		//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET:
		//ORIGINAL LINE: public com.google.zxing.Result decode(com.google.zxing.BinaryBitmap image, java.util.Map<com.google.zxing.DecodeHintType,?> hints) throws com.google.zxing.NotFoundException, com.google.zxing.ChecksumException, com.google.zxing.FormatException
		public Result decode(BinaryBitmap image, IDictionary<DecodeHintType, object> hints)
		{

			int width = image.Width;
			int height = image.Height;
			int halfWidth = width / 2;
			int halfHeight = height / 2;

			BinaryBitmap topLeft = image.crop(0, 0, halfWidth, halfHeight);
			try
			{
				return @delegate.decode(topLeft, hints);
			}
			catch (NotFoundException re)
			{
				// continue
			}

			BinaryBitmap topRight = image.crop(halfWidth, 0, halfWidth, halfHeight);
			try
			{
				return @delegate.decode(topRight, hints);
			}
			catch (NotFoundException re)
			{
				// continue
			}

			BinaryBitmap bottomLeft = image.crop(0, halfHeight, halfWidth, halfHeight);
			try
			{
				return @delegate.decode(bottomLeft, hints);
			}
			catch (NotFoundException re)
			{
				// continue
			}

			BinaryBitmap bottomRight = image.crop(halfWidth, halfHeight, halfWidth, halfHeight);
			try
			{
				return @delegate.decode(bottomRight, hints);
			}
			catch (NotFoundException re)
			{
				// continue
			}

			int quarterWidth = halfWidth / 2;
			int quarterHeight = halfHeight / 2;
			BinaryBitmap center = image.crop(quarterWidth, quarterHeight, halfWidth, halfHeight);
			return @delegate.decode(center, hints);
		}

		public void reset()
		{
			@delegate.reset();
		}

	}

	/// <summary>
	/// <p>Attempts to locate multiple barcodes in an image by repeatedly decoding portion of the image.
	/// After one barcode is found, the areas left, above, right and below the barcode's
	/// <seealso cref="ResultPoint"/>s are scanned, recursively.</p>
	/// 
	/// <p>A caller may want to also employ <seealso cref="ByQuadrantReader"/> when attempting to find multiple
	/// 2D barcodes, like QR Codes, in an image, where the presence of multiple barcodes might prevent
	/// detecting any one of them.</p>
	/// 
	/// <p>That is, instead of passing a <seealso cref="Reader"/> a caller might pass
	/// {@code new ByQuadrantReader(reader)}.</p>
	/// 
	/// @author Sean Owen
	/// </summary>
	public sealed class GenericMultipleBarcodeReader : MultipleBarcodeReader
	{

		private const int MIN_DIMENSION_TO_RECUR = 100;

		private readonly Reader @delegate;

		public GenericMultipleBarcodeReader(Reader @delegate)
		{
			this.@delegate = @delegate;
		}

		//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET:
		//ORIGINAL LINE: public com.google.zxing.Result[] decodeMultiple(com.google.zxing.BinaryBitmap image) throws com.google.zxing.NotFoundException
		public Result[] decodeMultiple(BinaryBitmap image)
		{
			return decodeMultiple(image, null);
		}

		//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET:
		//ORIGINAL LINE: public com.google.zxing.Result[] decodeMultiple(com.google.zxing.BinaryBitmap image, java.util.Map<com.google.zxing.DecodeHintType,?> hints) throws com.google.zxing.NotFoundException
		public Result[] decodeMultiple(BinaryBitmap image, IDictionary<DecodeHintType, object> hints)
		{
			List<Result> results = new List<Result>();
			doDecodeMultiple(image, hints, results, 0, 0);
			if (results.Count == 0)
			{
				throw NotFoundException.NotFoundInstance;
			}
			return results.ToArray();
		}

		private void doDecodeMultiple(BinaryBitmap image, IDictionary<DecodeHintType, object> hints, IList<Result> results, int xOffset, int yOffset)
		{
			Result result;
			try
			{
				result = @delegate.decode(image, hints);
			}
			catch (ReaderException re)
			{
				return;
			}
			bool alreadyFound = false;
			foreach (Result existingResult in results)
			{
				if (existingResult.Text.Equals(result.Text))
				{
					alreadyFound = true;
					break;
				}
			}
			if (!alreadyFound)
			{
				results.Add(translateResultPoints(result, xOffset, yOffset));
			}
			ResultPoint[] resultPoints = result.ResultPoints;
			if (resultPoints == null || resultPoints.Length == 0)
			{
				return;
			}
			int width = image.Width;
			int height = image.Height;
			float minX = width;
			float minY = height;
			float maxX = 0.0f;
			float maxY = 0.0f;
			foreach (ResultPoint point in resultPoints)
			{
				float x = point.X;
				float y = point.Y;
				if (x < minX)
				{
					minX = x;
				}
				if (y < minY)
				{
					minY = y;
				}
				if (x > maxX)
				{
					maxX = x;
				}
				if (y > maxY)
				{
					maxY = y;
				}
			}

			// Decode left of barcode
			if (minX > MIN_DIMENSION_TO_RECUR)
			{
				doDecodeMultiple(image.crop(0, 0, (int)minX, height), hints, results, xOffset, yOffset);
			}
			// Decode above barcode
			if (minY > MIN_DIMENSION_TO_RECUR)
			{
				doDecodeMultiple(image.crop(0, 0, width, (int)minY), hints, results, xOffset, yOffset);
			}
			// Decode right of barcode
			if (maxX < width - MIN_DIMENSION_TO_RECUR)
			{
				doDecodeMultiple(image.crop((int)maxX, 0, width - (int)maxX, height), hints, results, xOffset + (int)maxX, yOffset);
			}
			// Decode below barcode
			if (maxY < height - MIN_DIMENSION_TO_RECUR)
			{
				doDecodeMultiple(image.crop(0, (int)maxY, width, height - (int)maxY), hints, results, xOffset, yOffset + (int)maxY);
			}
		}

		private static Result translateResultPoints(Result result, int xOffset, int yOffset)
		{
			ResultPoint[] oldResultPoints = result.ResultPoints;
			if (oldResultPoints == null)
			{
				return result;
			}
			ResultPoint[] newResultPoints = new ResultPoint[oldResultPoints.Length];
			for (int i = 0; i < oldResultPoints.Length; i++)
			{
				ResultPoint oldPoint = oldResultPoints[i];
				newResultPoints[i] = new ResultPoint(oldPoint.X + xOffset, oldPoint.Y + yOffset);
			}
			return new Result(result.Text, result.RawBytes, newResultPoints, result.BarcodeFormat);
		}

	}

	/// <summary>
	/// Implementation of this interface attempt to read several barcodes from one image.
	/// </summary>
	/// <seealso cref= com.google.zxing.Reader
	/// @author Sean Owen </seealso>
	public interface MultipleBarcodeReader
	{

		//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET:
		//ORIGINAL LINE: com.google.zxing.Result[] decodeMultiple(com.google.zxing.BinaryBitmap image) throws com.google.zxing.NotFoundException;
		Result[] decodeMultiple(BinaryBitmap image);

		//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET:
		//ORIGINAL LINE: com.google.zxing.Result[] decodeMultiple(com.google.zxing.BinaryBitmap image, java.util.Map<com.google.zxing.DecodeHintType,?> hints) throws com.google.zxing.NotFoundException;
		Result[] decodeMultiple(BinaryBitmap image, IDictionary<DecodeHintType, object> hints);

	}

	/// <summary>
	/// This implementation can detect and decode multiple QR Codes in an image.
	/// 
	/// @author Sean Owen
	/// @author Hannes Erven
	/// </summary>
	public sealed class QRCodeMultiReader : QRCodeReader, MultipleBarcodeReader
	{

		private static readonly Result[] EMPTY_RESULT_ARRAY = new Result[0];

		//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET:
		//ORIGINAL LINE: public com.google.zxing.Result[] decodeMultiple(com.google.zxing.BinaryBitmap image) throws com.google.zxing.NotFoundException
		public Result[] decodeMultiple(BinaryBitmap image)
		{
			return decodeMultiple(image, null);
		}

		//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET:
		//ORIGINAL LINE: public com.google.zxing.Result[] decodeMultiple(com.google.zxing.BinaryBitmap image, java.util.Map<com.google.zxing.DecodeHintType,?> hints) throws com.google.zxing.NotFoundException
		public Result[] decodeMultiple(BinaryBitmap image, IDictionary<DecodeHintType, object> hints)
		{
			List<Result> results = new List<Result>();
			DetectorResult[] detectorResults = (new MultiDetector(image.BlackMatrix)).detectMulti(hints);
			foreach (DetectorResult detectorResult in detectorResults)
			{
				try
				{
					DecoderResult decoderResult = Decoder.decode(detectorResult.Bits, hints);
					ResultPoint[] points = detectorResult.Points;
					Result result = new Result(decoderResult.Text, decoderResult.RawBytes, points, BarcodeFormat.QR_CODE);
					IList<sbyte[]> byteSegments = decoderResult.ByteSegments;
					if (byteSegments != null)
					{
						result.putMetadata(ResultMetadataType.BYTE_SEGMENTS, byteSegments);
					}
					string ecLevel = decoderResult.ECLevel;
					if (ecLevel != null)
					{
						result.putMetadata(ResultMetadataType.ERROR_CORRECTION_LEVEL, ecLevel);
					}
					results.Add(result);
				}
				catch (ReaderException re)
				{
					// ignore and continue 
				}
			}
			if (results.Count == 0)
			{
				return EMPTY_RESULT_ARRAY;
			}
			else
			{
				return results.ToArray();
			}
		}

	}

	/// <summary>
	/// <p>Encapsulates logic that can detect one or more QR Codes in an image, even if the QR Code
	/// is rotated or skewed, or partially obscured.</p>
	/// 
	/// @author Sean Owen
	/// @author Hannes Erven
	/// </summary>
	public sealed class MultiDetector : Detector
	{

		private static readonly DetectorResult[] EMPTY_DETECTOR_RESULTS = new DetectorResult[0];

		public MultiDetector(BitMatrix image)
			: base(image)
		{
		}

		//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET:
		//ORIGINAL LINE: public com.google.zxing.common.DetectorResult[] detectMulti(java.util.Map<com.google.zxing.DecodeHintType,?> hints) throws com.google.zxing.NotFoundException
		public DetectorResult[] detectMulti(IDictionary<DecodeHintType, object> hints)
		{
			BitMatrix image = Image;
			//ResultPointCallback resultPointCallback = hints == null ? null : (ResultPointCallback) hints[DecodeHintType.NEED_RESULT_POINT_CALLBACK];
			ResultPointCallback resultPointCallback = null;
			if (hints != null && hints.ContainsKey(DecodeHintType.NEED_RESULT_POINT_CALLBACK))
			{
				resultPointCallback = (ResultPointCallback)hints[DecodeHintType.NEED_RESULT_POINT_CALLBACK];
			}

			MultiFinderPatternFinder finder = new MultiFinderPatternFinder(image, resultPointCallback);
			FinderPatternInfo[] infos = finder.findMulti(hints);

			if (infos.Length == 0)
			{
				throw NotFoundException.NotFoundInstance;
			}

			List<DetectorResult> result = new List<DetectorResult>();
			foreach (FinderPatternInfo info in infos)
			{
				try
				{
					result.Add(processFinderPatternInfo(info));
				}
				catch (ReaderException e)
				{
					// ignore
				}
			}
			if (result.Count == 0)
			{
				return EMPTY_DETECTOR_RESULTS;
			}
			else
			{
				return result.ToArray();
			}
		}

	}

	/// <summary>
	/// <p>This class attempts to find finder patterns in a QR Code. Finder patterns are the square
	/// markers at three corners of a QR Code.</p>
	/// 
	/// <p>This class is thread-safe but not reentrant. Each thread must allocate its own object.
	/// 
	/// <p>In contrast to <seealso cref="FinderPatternFinder"/>, this class will return an array of all possible
	/// QR code locations in the image.</p>
	/// 
	/// <p>Use the TRY_HARDER hint to ask for a more thorough detection.</p>
	/// 
	/// @author Sean Owen
	/// @author Hannes Erven
	/// </summary>
	internal sealed class MultiFinderPatternFinder : FinderPatternFinder
	{

		private static readonly FinderPatternInfo[] EMPTY_RESULT_ARRAY = new FinderPatternInfo[0];

		// TODO MIN_MODULE_COUNT and MAX_MODULE_COUNT would be great hints to ask the user for
		// since it limits the number of regions to decode

		// max. legal count of modules per QR code edge (177)
		private const float MAX_MODULE_COUNT_PER_EDGE = 180;
		// min. legal count per modules per QR code edge (11)
		private const float MIN_MODULE_COUNT_PER_EDGE = 9;

		/// <summary>
		/// More or less arbitrary cutoff point for determining if two finder patterns might belong
		/// to the same code if they differ less than DIFF_MODSIZE_CUTOFF_PERCENT percent in their
		/// estimated modules sizes.
		/// </summary>
		private const float DIFF_MODSIZE_CUTOFF_PERCENT = 0.05f;

		/// <summary>
		/// More or less arbitrary cutoff point for determining if two finder patterns might belong
		/// to the same code if they differ less than DIFF_MODSIZE_CUTOFF pixels/module in their
		/// estimated modules sizes.
		/// </summary>
		private const float DIFF_MODSIZE_CUTOFF = 0.5f;


		/// <summary>
		/// A comparator that orders FinderPatterns by their estimated module size.
		/// </summary>
		[Serializable]
		private sealed class ModuleSizeComparator : IComparer<com.google.zxing.qrcode.detector.FinderPattern>
		{
			public int Compare(FinderPattern center1, FinderPattern center2)
			{
				float value = center2.EstimatedModuleSize - center1.EstimatedModuleSize;
				return value < 0.0 ? -1 : value > 0.0 ? 1 : 0;
			}
		}

		/// <summary>
		/// <p>Creates a finder that will search the image for three finder patterns.</p>
		/// </summary>
		/// <param name="image"> image to search </param>
		internal MultiFinderPatternFinder(BitMatrix image)
			: base(image)
		{
		}

		internal MultiFinderPatternFinder(BitMatrix image, ResultPointCallback resultPointCallback)
			: base(image, resultPointCallback)
		{
		}

		/// <returns> the 3 best <seealso cref="FinderPattern"/>s from our list of candidates. The "best" are
		///         those that have been detected at least <seealso cref="#CENTER_QUORUM"/> times, and whose module
		///         size differs from the average among those patterns the least </returns>
		/// <exception cref="NotFoundException"> if 3 such finder patterns do not exist </exception>
		//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET:
		//ORIGINAL LINE: private com.google.zxing.qrcode.detector.FinderPattern[][] selectMutipleBestPatterns() throws com.google.zxing.NotFoundException
		private FinderPattern[][] selectMutipleBestPatterns()
		{
			List<FinderPattern> possibleCenters = PossibleCenters;
			int size = possibleCenters.Count;

			if (size < 3)
			{
				// Couldn't find enough finder patterns
				throw NotFoundException.NotFoundInstance;
			}

			//Begin HE modifications to safely detect multiple codes of equal size
			if (size == 3)
			{
				return new FinderPattern[][] { new FinderPattern[] { possibleCenters[0], possibleCenters[1], possibleCenters[2] } };
			}

			// Sort by estimated module size to speed up the upcoming checks
			possibleCenters.Sort(new ModuleSizeComparator());

			// Now lets start: build a list of tuples of three finder locations that
			//  - feature similar module sizes
			//  - are placed in a distance so the estimated module count is within the QR specification
			//  - have similar distance between upper left/right and left top/bottom finder patterns
			//  - form a triangle with 90° angle (checked by comparing top right/bottom left distance
			//    with pythagoras)
			//
			// Note: we allow each point to be used for more than one code region: this might seem
			// counterintuitive at first, but the performance penalty is not that big. At this point,
			// we cannot make a good quality decision whether the three finders actually represent
			// a QR code, or are just by chance layouted so it looks like there might be a QR code there.
			// So, if the layout seems right, lets have the decoder try to decode.     
			List<FinderPattern[]> results = new List<FinderPattern[]>(); // holder for the results

			for (int i1 = 0; i1 < (size - 2); i1++)
			{
				FinderPattern p1 = possibleCenters[i1];
				if (p1 == null)
				{
					continue;
				}

				for (int i2 = i1 + 1; i2 < (size - 1); i2++)
				{
					FinderPattern p2 = possibleCenters[i2];
					if (p2 == null)
					{
						continue;
					}

					// Compare the expected module sizes; if they are really off, skip
					float vModSize12 = (p1.EstimatedModuleSize - p2.EstimatedModuleSize) / Math.Min(p1.EstimatedModuleSize, p2.EstimatedModuleSize);
					float vModSize12A = Math.Abs(p1.EstimatedModuleSize - p2.EstimatedModuleSize);
					if (vModSize12A > DIFF_MODSIZE_CUTOFF && vModSize12 >= DIFF_MODSIZE_CUTOFF_PERCENT)
					{
						// break, since elements are ordered by the module size deviation there cannot be
						// any more interesting elements for the given p1.
						break;
					}

					for (int i3 = i2 + 1; i3 < size; i3++)
					{
						FinderPattern p3 = possibleCenters[i3];
						if (p3 == null)
						{
							continue;
						}

						// Compare the expected module sizes; if they are really off, skip
						float vModSize23 = (p2.EstimatedModuleSize - p3.EstimatedModuleSize) / Math.Min(p2.EstimatedModuleSize, p3.EstimatedModuleSize);
						float vModSize23A = Math.Abs(p2.EstimatedModuleSize - p3.EstimatedModuleSize);
						if (vModSize23A > DIFF_MODSIZE_CUTOFF && vModSize23 >= DIFF_MODSIZE_CUTOFF_PERCENT)
						{
							// break, since elements are ordered by the module size deviation there cannot be
							// any more interesting elements for the given p1.
							break;
						}

						FinderPattern[] test = { p1, p2, p3 };
						ResultPoint.orderBestPatterns(test);

						// Calculate the distances: a = topleft-bottomleft, b=topleft-topright, c = diagonal
						FinderPatternInfo info = new FinderPatternInfo(test);
						float dA = ResultPoint.distance(info.TopLeft, info.BottomLeft);
						float dC = ResultPoint.distance(info.TopRight, info.BottomLeft);
						float dB = ResultPoint.distance(info.TopLeft, info.TopRight);

						// Check the sizes
						float estimatedModuleCount = (dA + dB) / (p1.EstimatedModuleSize * 2.0f);
						if (estimatedModuleCount > MAX_MODULE_COUNT_PER_EDGE || estimatedModuleCount < MIN_MODULE_COUNT_PER_EDGE)
						{
							continue;
						}

						// Calculate the difference of the edge lengths in percent
						float vABBC = Math.Abs((dA - dB) / Math.Min(dA, dB));
						if (vABBC >= 0.1f)
						{
							continue;
						}

						// Calculate the diagonal length by assuming a 90° angle at topleft
						float dCpy = (float)Math.Sqrt(dA * dA + dB * dB);
						// Compare to the real distance in %
						float vPyC = Math.Abs((dC - dCpy) / Math.Min(dC, dCpy));

						if (vPyC >= 0.1f)
						{
							continue;
						}

						// All tests passed!
						results.Add(test);
					} // end iterate p3
				} // end iterate p2
			} // end iterate p1

			if (results.Count > 0)
			{
				return results.ToArray();
			}

			// Nothing found!
			throw NotFoundException.NotFoundInstance;
		}

		//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET:
		//ORIGINAL LINE: public com.google.zxing.qrcode.detector.FinderPatternInfo[] findMulti(java.util.Map<com.google.zxing.DecodeHintType,?> hints) throws com.google.zxing.NotFoundException
		public FinderPatternInfo[] findMulti(IDictionary<DecodeHintType, object> hints)
		{
			bool tryHarder = hints != null && hints.ContainsKey(DecodeHintType.TRY_HARDER);
			BitMatrix image = Image;
			int maxI = image.Height;
			int maxJ = image.Width;
			// We are looking for black/white/black/white/black modules in
			// 1:1:3:1:1 ratio; this tracks the number of such modules seen so far

			// Let's assume that the maximum version QR Code we support takes up 1/4 the height of the
			// image, and then account for the center being 3 modules in size. This gives the smallest
			// number of pixels the center could be, so skip this often. When trying harder, look for all
			// QR versions regardless of how dense they are.
			int iSkip = (int)(maxI / (MAX_MODULES * 4.0f) * 3);
			if (iSkip < MIN_SKIP || tryHarder)
			{
				iSkip = MIN_SKIP;
			}

			int[] stateCount = new int[5];
			for (int i = iSkip - 1; i < maxI; i += iSkip)
			{
				// Get a row of black/white values
				stateCount[0] = 0;
				stateCount[1] = 0;
				stateCount[2] = 0;
				stateCount[3] = 0;
				stateCount[4] = 0;
				int currentState = 0;
				for (int j = 0; j < maxJ; j++)
				{
					if (image.get(j, i))
					{
						// Black pixel
						if ((currentState & 1) == 1) // Counting white pixels
						{
							currentState++;
						}
						stateCount[currentState]++;
					} // White pixel
					else
					{
						if ((currentState & 1) == 0) // Counting black pixels
						{
							if (currentState == 4) // A winner?
							{
								if (foundPatternCross(stateCount)) // Yes
								{
									bool confirmed = handlePossibleCenter(stateCount, i, j);
									if (!confirmed)
									{
										do // Advance to next black pixel
										{
											j++;
										} while (j < maxJ && !image.get(j, i));
										j--; // back up to that last white pixel
									}
									// Clear state to start looking again
									currentState = 0;
									stateCount[0] = 0;
									stateCount[1] = 0;
									stateCount[2] = 0;
									stateCount[3] = 0;
									stateCount[4] = 0;
								} // No, shift counts back by two
								else
								{
									stateCount[0] = stateCount[2];
									stateCount[1] = stateCount[3];
									stateCount[2] = stateCount[4];
									stateCount[3] = 1;
									stateCount[4] = 0;
									currentState = 3;
								}
							}
							else
							{
								stateCount[++currentState]++;
							}
						} // Counting white pixels
						else
						{
							stateCount[currentState]++;
						}
					}
				} // for j=...

				if (foundPatternCross(stateCount))
				{
					handlePossibleCenter(stateCount, i, maxJ);
				} // end if foundPatternCross
			} // for i=iSkip-1 ...
			FinderPattern[][] patternInfo = selectMutipleBestPatterns();
			List<FinderPatternInfo> result = new List<FinderPatternInfo>();
			foreach (FinderPattern[] pattern in patternInfo)
			{
				ResultPoint.orderBestPatterns(pattern);
				result.Add(new FinderPatternInfo(pattern));
			}

			if (result.Count == 0)
			{
				return EMPTY_RESULT_ARRAY;
			}
			else
			{
				return result.ToArray();
			}
		}

	}

	*/
}
